re-initialize an object in same variable

  • Thread starter Thread starter Guest
  • Start date Start date
G

Guest

Hi,

When I use same variable for a new created object, then whill the old one
destroyed by garbage collection, or do I first have to set it to null ?

eg:

SomeObject o = new SomeObject();
// and a while later:
o = new SomeObject();

or should I do:
o = null; // or call destructor? how?
o = new SomeObject();
 
Hi Wilfried,

You should call Dispose, if that class supports it, before replacing the
instance.
 
There is no need to set the variable to null prior to changing it's
value. The only thing that matters to the garbage collector in this
scenario is that there no longer are any references to the instance that
was created first.

As to when the garbage collector actually collects the now unused
object, you don't know. It depends on how much more memory your
application is allocating.

As Miha said, if your object are referencing any resources that you need
to explicitly destroy at the time you stop referencing your object, you
should have the object implement IDispose and call that object's Dispose
method.

Regards,
Joakim
 
Hi Miha,
You should call Dispose, if that class supports it, before replacing the
instance.

It dont supports it :( It is little class from my own. If I write a
destructor then it is not called. It is called only when I do a new into a
stack variable wich seems logical.

It does not allocate memory, but it holds some public variables calculated
at creation time. This means I have a memory leak when calling new 2 time?

How do I implement a Dispose method ? I read that a destructor cannot be
called just like that?
 
What do you mean with " it holds public variables"? If these hold values,
those will be gone with the object when it gets collected. If they hold
references, those will get collected when the GC comes along too. Thers is
no leak, and there's no need to Dispose.

Willy.
 
Hi Wilfried,

I was generaly speaking. If the class implements IDisposable (Dispose
method) you should call it before loosing the instance. If it doesn't then
you don't need to call anything (well, actually depends on the class
implementation - well behaved classes would have IDisposable).
You need to implement IDisposable (and thus Dispose) only if you want to do
some clean up or close valuable resources.
In your case, you don't need to implement it because you don't hold any such
resource - that variable of yours will be collected by garbage collector
when all references to holding class are lost (when you assing new instance
to your variable o).

So, in your case, there is no need to do anything (call Dispose or set
variable to null) - just assign new instance.
 
Back
Top