Should I assign null to my local variables?

Q: Should I assign null to my local variables after I use them?

For example:

string s = ...;
Console.WriteLine(s);
s = null;

A: There is rarely a need to do this for local variables in C#

The lifetime of variables is tracked by the JIT - it analyzes how variables are used in a routine, and it knows exactly when the variable is no longer needed, and after that point, the value is available to be collected.

Interestingly, if you assign it to null, you are actually extending the lifetime of the variable slightly, so it could cause it to be garbage collected later (though realistically, there's unlikely to be any real difference here.

This is true for the vast majority of methods. If you have a method where your code lives for a while - a loop on a separate thread, for example - then it may be worthwhile to see if there are any unnecessary values living in variables while you wait.

 

 

 

 

 

 

 

[Author: Eric Gunnerson]