Using Dispose and/or null on objects

Cavar

Well-known member
Joined
Sep 5, 2006
Messages
60
Programming Experience
5-10
This is a general .NET question, but I provided C# code.

If I have an object that implements IDisposable and I call the .Dispose method, should I also set the object to null? I know about the "using" keyword, so no need to explain it or it's benefits.

Ex:

Should I do this...

VB.NET:
SqlCommand cmd = new SqlCommand();

...do stuff with command here....

cmd.Dispose();

cmd = null;

...or...

VB.NET:
SqlCommand cmd = new SqlCommand();

...do stuff with command here....

cmd.Dispose();

...or...

VB.NET:
SqlCommand cmd = new SqlCommand();

...do stuff with command here....

cmd = null;

Thanks in advance.
CT
 
This is a general .NET question, but I provided C# code.
It is most appropriate to provide VB.Net code when you post to VB.Net Forums.

If an object implements IDisposable you should call its Dispose method after using it in code. Controls/component on form are disposed when form is. Setting variable to Nothing serve no purpose if variable goes out of scope. Something from the documentation about object lifetime:
The only time you should set a variable to Nothing is when its lifetime is long relative to the time the garbage collector takes to detect orphaned objects.
 
Back
Top