|
-
Jun 29th, 2007, 11:57 PM
#1
Thread Starter
Addicted Member
[RESOLVED] Using Dispose and/or null on objects
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 benefits the "using" keyword, so no need to explain it.
Ex:
Should I do this...
Code:
SqlCommand cmd = new SqlCommand();
...do stuff with command here....
cmd.Dispose();
cmd = null;
...or...
Code:
SqlCommand cmd = new SqlCommand();
...do stuff with command here....
cmd.Dispose();
...or...
Code:
SqlCommand cmd = new SqlCommand();
...do stuff with command here....
cmd = null;
Thanks in advance.
CT
-
Jun 30th, 2007, 01:11 AM
#2
Re: Using Dispose and/or null on objects
The best way to do it is:
Code:
SqlCommand cmd = new SqlCommand();
try{
...do stuff with command here....
}
catch{
}
finally{
cmd.Dispose();
}
which is like the "using" keyword that you already know but won't use
"I'm not normally a praying man, but if you're up there, save me... Superman!" - Homer Simpson
My Blog
-
Jun 30th, 2007, 05:29 AM
#3
Re: Using Dispose and/or null on objects
You can't possibly set an object to null. An object is an object and it is always an object. Variables refer to objects and you can set variables to null. Any object that you create should be disposed when you're done with it if it supports it. Disposing an object releases its unmanaged resources.
Setting a variable to null is something else. Doing so removes that reference to the object from the system. If that was the last reference to that object, i.e. the last variable that referred to that object, then the object is flagged as available for garbage collection. Setting variables to null is usually pointless. If it is a local variable and it loses scope soon after then the reference is removed then anyway. You would only need to set a variable to null if it will not, or may not, lose scope for some time. That would include member variables or local variables in long-running methods.
-
Jun 30th, 2007, 08:53 AM
#4
Thread Starter
Addicted Member
Re: Using Dispose and/or null on objects
Thanks for clearing that up, I've been using both on objects that support .Dispose and now I'll be a ble to save a few keystrokes and make the code cleaner.
CT
Posting Permissions
- You may not post new threads
- You may not post replies
- You may not post attachments
- You may not edit your posts
-
Forum Rules
|
Click Here to Expand Forum to Full Width
|