views:

1972

answers:

11

Should you set all the objects to null (Nothing in VB.NET) once you have finished with them?

I understand that in .NET it is essential to dispose of any instances of objects that implement the Idisposable interface to release some resources. Although the object can still be something after it is disposed (hence the isDisposed property in forms) so I assume it can still reside in memory or at least in part?

I also know that when an object goes out of scope it is then marked for collection ready for the next pass of the garbage collector (although this may take time).

So with this in mind will setting it to null speed up the system releasing the memory as it does not have to work out that it is no longer in scope and are they any bad side effects?

MSDN articles never do this in examples and currently I do this as I cannot see the harm. However I have come across a mixture of opinions so any comments are useful.

A: 

Some object suppose the .dispose() method which forces the resource to be removed from memory.

GateKiller
No it doesn't; Dispose() does *not* collect the object - it is used to perform deterministic clean up, typically releasing unmanaged resources.
Marc Gravell
+1  A: 

No don't null objects. You can check out http://codebetter.com/blogs/karlseguin/archive/2008/04/27/foundations-of-programming-pt-7-back-to-basics-memory.aspx for more information, but setting things to null won't do anything, except dirty your code.

Karl Seguin
A: 

The only time you should set a variable to null is when the variable does not go out of scope and you no longer need the data associated with it. Otherwise there is no need.

Bob
+4  A: 

The only time you should set a variable to null is when the variable does not go out of scope and you no longer need the data associated with it. Otherwise there is no need.

That's true, but it also means you should probably refactor your code. I don't think I've ever needed to declare a variable outside of it's intended scope.

Karl Seguin
+3  A: 

Also:

using(SomeObject object = new SomeObject()) 
{
  // do stuff with the object
}
// the object will be disposed of
Steve Tranby
A: 

There are some cases where it makes sense to null references. For instance, when you're writing a collection--like a priority queue--and by your contract, you shouldn't be keeping those objects alive for the client after the client has removed them from the queue.

But this sort of thing only matters in long lived collections. If the queue's not going to survive the end of the function it was created in, then it matters a whole lot less.

On a whole, you really shouldn't bother. Let the compiler and GC do their jobs so you can do yours.

Patrick
+12  A: 

Karl is absolutely correct, there is no need to set objects to null after use. If an object implements IDisposable, just make sure you call IDisposable.Dispose() when you're done with that object (wrapped in a try..finally, or, a using() block). But even if you don't remember to call Dispose, the finaliser method on the object should be calling Dispose() for you.

I thought this was a good treatment:

http://msdn.microsoft.com/en-us/magazine/cc163392.aspx

and this

http://www.marcclifton.com/tabid/79/Default.aspx

There isn't any point in trying to second guess the GC and its management strategies because it's self tuning and opaque. There was a good discussion about the inner workings with Jeffrey Richter on Dot Net Rocks here: http://www.dotnetrocks.com/default.aspx?showNum=361 and Richters book CLR via C# chapter 20 has a great treatment:

Kev
The rule about not setting to null isn't "hard and fast"...if the object gets put on the large object heap (size is >85K) it will help the GC if you set the object to null when you are done using it.
Scott Dorman
I agree to a limited extent, but unless you're starting to experience memory pressure then I see no need to 'prematurely optimise' by setting objects to null after use.
Kev
This whole business of "don't prematurely optimize" sounds more like "Prefer slow and don't worry because CPUs are getting faster and CRUD apps don't need speed anyway." It may just be me though. :)
BobbyShaftoe
+1  A: 

In general, there's no need to null objects after use, but in some cases I find it's a good practice.

If an object implements IDisposable and is stored in a field, I think it's good to null it, just to avoid using the disposed object. The bugs of the following sort can be painful:

this.myField.Dispose();
// ... at some later time
this.myField.DoSomething();

It's good to null the field after disposing it, and get a NullPtrEx right at the line where the field is used again. Otherwise, you might run into some cryptic bug down the line (depending on exactly what DoSomething does).

dbkk
+1  A: 

Chances are that your code is not structured tightly enough if you feel the need to null variables.

There are a number of ways to limit the scope of a variable:

As mentioned by Steve Tranby

using(SomeObject object = new SomeObject()) 
{
// do stuff with the object
}
// the object will be disposed of

Similarly, you can simply use curly brackets:

{
// Declare the variable and use it
SomeObject object = new SomeObject()
}
// The variable is no longer available

I find that using curly brackets without any "heading" to really clean out the code and help make it more understandable.

GoodEnough
+1  A: 

Another reason to avoid setting objects to null when you are done with them is that it can actually keep them alive for longer.

e.g.

void foo()
{
    var someType = new SomeType();
    someType.DoSomething();
    // someType is now eligible for garbage collection         

    // ... rest of method not using 'someType' ...
}

will allow the object referred by someType to be GC'd after the call to "DoSomething" but

void foo()
{
    var someType = new SomeType();
    someType.DoSomething();
    // someType is NOT eligible for garbage collection yet
    // because that variable is used at the end of the method         

    // ... rest of method not using 'someType' ...
    someType = null;
}

may sometimes keep the object alive until the end of the method. The JIT will usually optimized away the assignment to null, so both bits of code end up being the same.

Wilka
A: 

Take a look at this article as well: http://www.codeproject.com/KB/cs/idisposable.aspx

For the most part, setting an object to null has no effect. The only time you should be sure to do so is if you are working with a "large object", which is one larger than 84K in size (such as bitmaps).

Scott Dorman