If the variable is local to the current scope, is there any reason to set them to null right before the end of it?
{
var com = new AComponentObjectModelInterface();
// something goes here
// ...
com = null; // why?
}
If the variable is local to the current scope, is there any reason to set them to null right before the end of it?
{
var com = new AComponentObjectModelInterface();
// something goes here
// ...
com = null; // why?
}
Short answer, No, not in C#
This is often a habit developers take using other languages like VB6
Setting a variable to null is NOT disposing of the object it references to. In fact it may hinder garbage collection by extending the scope of the variable.
Short answer: In your particular case, there is no reason whatsoever. Most likely those programmers came from a different language where that made sense.
It's sometimes useful to prevent multiple Dispose
of the same object. Say you have a Close
method that does some clean-up on your class. By setting the object to null
, you'll ensure multiple Close
call won't try to Dispose
the DisposableMember
multiple times:
public void Close()
{
if (DisposableMember != null)
{
DisposableMember.Dispose();
DisposableMember = null;
}
}
But keep in mind it doesn't free/dispose anything itself.
Maybe the developer that used this was migrating VB6 code manually. But he ignored that
Set aComponentObjectModelInstance = new AComponentObjectModelInterface
// something goes here
// ...
Set aComponentObjectModelInstance = Nothing
should be translated to
var aComponentObjectModelInstance = new AComponentObjectModelInterface();
try
{
// something goes here
// ...
}
finally
{
Marshal.ReleaseComObject(aComponentObjectModelInstance);
}
instead