Setting Objects to Null/Nothing After Use in .Net

Setting Objects to Null/Nothing after use in .NET

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:

Digging into IDisposable

and this

Understanding IDisposable

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: Jeffrey Richter on the Windows Memory Model and
Richters book CLR via C# chapter 20 has a great treatment:

C# setting object as null

You can use nullable types to do this:

Vector3? vector = null;

And assign its value from some place:

position = new Vector3();

And then you can easily compare it to null as you would have compared a reference type object:

if(position != null) //or position.HasValue if you want
{
//...
}

After you verify it is not null, to access the Vector3 value, you should use position.Value.

Is there any reason to set an object to null in the finally block?

This is dependent on scope.

In your given example, o is only defined within the scope of the property. So it will be useless. However, say o was within the scope of the class. Then it MIGHT make sense to denote the state of o.

As it is currently, it is NOT needed.

Is there a reason why objects should be set to null after use?

Actually it is not handled automatically.

The issue being that as long as for example oDU is referenced, it can not be collected. Which means that basically if your holding object is not collected then references can not be collected. GOod style is to clear references when you do not need them anymore. At least for class / struct level variables.

Now, in this particular case it is totally not needed. The GC has nothing to do with this.

What has to do with this is that all these variables are local to the method, so they go out of scope anyway at the end of the method (and in runtime earlier, once they fall out of scope).

As such it is simply totally redundant.

Is it necessary to release memory by set obj to null in c#?

No, it won't do it immediately, and no, it's usually unnecessary if you're writing your code the right way.

If you have a resource that implements IDisposable, call Dispose() on it, or even better, put it in a using(...) block - it's much faster and will release the proper resources. If you have several large objects in the same scope that aren't COM objects or don't implement some form of disposal mechanism, doing:

someObject = null;
GC.Collect();

might help, but you're probably better off restructuring your code so you don't end up in that situation.

If you're doing this before objects go out of scope, it's completely superfluous and makes things worse. More so if you set things to null in your finalizer. For example, never do this:

public void aFunction() {
SomeThing anObject = new SomeThing();
// ...
anObject = null;
}

nor this:

public ~MyClass() {
this.Something = null; // WRONG!
this.SomethingElse.Dispose(); // DANGEROUS!
this.SomeObject.Notify("I got finalized!"); // ALSO DANGEROUS!
}

And, for the sake of completeness, you do this:

Marshal.ReleaseComObject(someObj);

to release a COM object.

Setting a variable to null when its no longer needed

Everybody is quick to dismiss this, but it is not actually entirely useless. Most code that sets an object to null gets optimized away by the jitter optimizer, not this one. Because it sets a field to null, not a local variable.

There are corner cases where dropping the reference to an array can pay off. Especially so when the array is large, more than 21250 elements. Setting the array reference to null allows it to be garbage collected early, earlier than would normally happen. Which is when the "someclass" object gets garbage collected.

Then again, in this specific case you'd better not have tens of thousands of elements in the array, that would put a lot of pressure on the threadpool. So ideally this would be a micro-optimization whose effect you'll never notice.

Setting objects to nothing

You're basically doing the right thing. After you call .Dispose(), you can be sure that the resources allocated by the connection are cleaned up. Then, as soon as the SqlConnection object you declared in code goes out of scope, the GC will clean up that memory as well.

If you'd like to prod the GC, you can always call its .Collect() method.

Any sense to set obj = null(Nothing) in Dispose()?

The purpose of Dispose() is to allow clean up of resources that are not handled by the garbage collector. Objects are taken care of by GC, so there's really no need to set the reference to null under normal circumstances.

The exception is if you expect the caller to call Dispose and hold on to the instance after that. In that case, it can be a good idea to set the internal reference to null. However, disposable instances are typically disposed and released at the same time. In these cases it will not make a big difference.



Related Topics



Leave a reply



Submit