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?
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.
No. When it comes to local variables it makes no difference at all if you have a reference to the object or not, what matters is if the reference will be used or not.
Putting an extra null assignment in the code doesn't hurt performance much, and it doesn't affect memory management at all, but it will add unmotivated statements to the code that makes it less readable.
The garbage collector knows when the reference is used the last time in the code, so it can collect the object as soon as it's not needed any more.
Example:
{
// Create an object
StringBuilder b = new StringBuilder();
b.Append("asdf");
// Here is the last use of the object:
string x = b.ToString();
// From this point the object can be collected whenever the GC feels like it
// If you assign a null reference to the variable here is irrelevant
b = null;
}