C#: should object variables be assigned to null?

In C#, is it necessary to assign an object variable to null if you have finished using it, even when it will go out of scope anyway?


No, and that could in fact be dangerous and bug-prone (consider the possibility that someone might try to use it later on, not realizing it had been set to null). Only set something to null if there's a logical reason to set it to null.


What matters more IMO is to call Dispose on objects that implement IDisposable.

Apart from that, assigning null to reference variables will just means that you are explicitly indicating end of scope - most of times, its just few instruction early (for example, local variables in method body) - with era of compiler/JIT optimizations, its quite possible that runtime would do the same, so you really don;t get anything out of it. In few cases, such as static variables etc (whose scope is application level), you should assign variable to null if you are done using it so that object will get garbage collected.


Should you turn off your car before pushing it to the lake?
No. It is a common mistake, but it doesn't make any difference. You aren't setting the object to null, just one reference to it - the object is still in memory, and must still be collected by the garbage collector.


Most of these responses have the right answer, but for the wrong reasons.

If it's a local variable, the variable will fall off the stack at the end of the method and therefore the object it was pointing to will have one less reference. If that variable was the only reference to the object, then the object is available for GC.

If you set the variable to null (and many who do were taught to do it at the end of the method) then you could actually wind up extending the time the object stays in memory because the CLR will believe that the object can't be collected until the end of the method because it sees a code reference to the object way down there. However, if you omit the setting of null the CLR can determine that no more calls for the object appear after a certain point in your code and, even though the method hasn't completed yet, the GC can collect the object.