2

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?
}
Jader Dias
  • 88,211
  • 155
  • 421
  • 625

5 Answers5

3

Short answer, No, not in C#

This is often a habit developers take using other languages like VB6

vc 74
  • 37,131
  • 7
  • 73
  • 89
  • I saw this in VB6 too, is there any reason to do that in VB? – Jader Dias Feb 03 '12 at 10:44
  • 1
    In VB6, yes, it causes COM references to be released. – Damien_The_Unbeliever Feb 03 '12 at 10:45
  • It is not necessary to set the object to Nothing in VB6 either, the object will be dereferenced as soon as it is out of scope. The issue of cleaning up COM objects in the CLR can get quite complex but if you are just creating and finishing with it in one method the answer provided by @XMLforDummies would dereference the object and should cause it to be removed from memory otherwise you just have to wait for the GC to clean it up. In other cases you should remember that the CLR doesn’t do reference counting and such dereferencing an object can remove the object from memory prenatally. – Robert Feb 06 '12 at 12:09
2

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.

Hans Kesting
  • 38,117
  • 9
  • 79
  • 111
1

Short answer: In your particular case, there is no reason whatsoever. Most likely those programmers came from a different language where that made sense.

Daniel Hilgarth
  • 171,043
  • 40
  • 335
  • 443
1

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.

ken2k
  • 48,145
  • 10
  • 116
  • 176
1

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

Jader Dias
  • 88,211
  • 155
  • 421
  • 625