detroy an object??

  • Thread starter Thread starter Tiago Costa
  • Start date Start date
T

Tiago Costa

Hi all!!!

My problem is this:

When i build an object, and after i used, should i destroy the obejct (like
the dispose method)

Or just this command is enouth:
object = null;


Thanks in advance
 
If the object implements IDisposable, call Dispose(). Otherwise, you
generally don't need to do anything else -- the garbage collector will
handle it for you.

Ken
 
Hi Tiago,

Tiago Costa said:
Hi all!!!

My problem is this:

When i build an object, and after i used, should i destroy the obejct
(like
the dispose method)

Or just this command is enouth:
object = null;

In general, you should just let the GC (Garbage Collector) do its work, you
do not need to delete the object by yourself - this is why the .NET
plattform is
called "managed"; the GC takes care of the memory management for you.

The exception to the rule: if you hold handles/etc. to unmanaged/native
code,
you should implement the IDisposable pattern in your code, and remember
to call Dispose() - or use the using() {} language construction in c# to
release
the unmanaged memory when your finished using it.
 
You can only dispose of objects that implement IDisposable. And the only
objects that implement IDisposable are those that are responsible for
unmanaged resources such as file I/O or database handles.

For IDisposable objects, by the way, don't overlook the "using (objectName)
{}" code blocks, which are very handy.

For all other objects, I don't do anything special although now and then if
I have a fairly large object that I can discard early in a routine I might
explicitly set it to null. The only benefit to that is that if garbage
collection occurs before the routine exits, that discarded object's memory
can be reclaimed immediately rather than at some later time.

For the most part, though, object lifetime is non-deterministic and you have
to trust the garbage collector to do its job. The whole idea of a
garbage-collected environment like C# is that you can focus on the problem
domain of the application and not be distracted with the need to manage
memory.

--Bob
 
that is actually unnecessary, in release mode, the JIT compiler is smart enough to figure this out for you when a reference is last accessed, and it will be elligible for GC right after.

For local variables the JIT is smart enough. Doing this for an
instance or static variable might make sense in *extreme*
circumstances.
 
Thanks, gents, I wondered how smart the JIT was and suspected that I was
being overly cautious.

I only do this in very limited circumstances, anyway, as you suggest -- if,
say, I had a huge Hashtable hanging around and no longer needed, but still
reachable in the object graph.

--Bob

enough to figure this out for you when a reference is last accessed, and it
will be elligible for GC right after.
 
Back
Top