Should I assign null to my local variables?

Should I assign null to my local variables?

  • Comments 14

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]

Leave a Comment
  • Please add 8 and 6 and type the answer here:
  • Post
Page 1 of 1 (14 items)