object clean up ?

G

Guest

Hi all,
I just want to know the difference between

1. When i use objEmployee = null

and

2. I inherit the class from IDisposable interface and implement Dispose
method.

Which is good practice and how CLR work in both the cases..

Thanks in advance
Andy
 
B

Brock Allen

You should call IDisposable.Dispose() to inform the object you're done with
it and it should do any cleanup it needs to immediaetly. Setting the reference
to null doesn't inform the object in any way. Back in the VB6 days, setting
a reference = Nothing actually called a method on the object, but it doesn't
work that way in .NET.

-Brock
DevelopMentor
http://staff.develop.com/ballen
 
C

Chris Mayers

Hi Andy,

I'm also still trying to get my head round this, so hopefully someone will
correct me is I have anything wrong...

AS far as I understand, if you do objEmployee = null
then all you are doing is destroying the pointer to the object 'objEmployee'
the actual object does not get affected. HOWEVER, assuming nothing else is
referencing the object then the CLR Garbage Collector should, at some point
realise that the object is un-referenced and will reclaim the memory.

The only problem is that if objEmployee does some 'complicated' stuff like
reference an external object, or open a database connection etc. then simply
by you removing the reference to it (objEmployee=null) the Garbage collector
may not be able to reclaim the memory.
This is where you could implement the Dispose method, which would do all the
necessary tidying up (close connections, dispose of external objects etc.)
so that the GC could neatly dispose of the unused object.

So I think depending on the circumstances you may need to use Dispose.
Though simple objects should sort themselves out. You don't normally need to
set the object to null as it may be reclaimed as soon as it goes out of
scope anyway.

Hope that makes some sort of sense...

Chris.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top