Search code examples
c#.netcom-interopdisposing

Is there any case where we have to set variables to null in C# when disposing them?


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?
}

Solution

  • 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