Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations derfloh on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Set variable=null ?

Status
Not open for further replies.

stuartd

Programmer
Joined
Jan 8, 2001
Messages
146
Location
US
Hi,

I know that c# has automatic garbage collection, but i have seen some code like this:

object o = new object;
...
{code to use object}
...
o=null;

Is the "o=null;" required or recommended?

SD
 
This really shouldn't be done for the purpose of garbage collection. Let C# do it for you.
 
Do you know what the purpose of that line is?

SD
 
Though there is nothing wrong with setting an object in memory to null when you are no longer going to use it. If it is huge it may make a difference.
Marty
 
Its useful when the variable will no longer be used, but the scope its in (method, etc) won't end (fire garbage collection) soon. Say you have this huge object that hogs up resources, and you are done using it, but still have a lot more code to run in that method. Then it could be benificial to set it to null.
 
Say you have this huge object that hogs up resources
Then the object should implement IDisposable, and the caller should call .Dispose() on it when it's done using it (or surround it with a using block)

Chip H.


____________________________________________________________________
Donate to Katrina relief:
If you want to get the best response to a question, please read FAQ222-2244 first
 
Chip,
Does using the Dispose() or the using block have a benifit over just setting it to null? Or is it just better practice.
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top