Setting Objects to Null/Nothing after use in .NET

后端 未结 15 2305
囚心锁ツ
囚心锁ツ 2020-11-22 16:09

Should you set all the objects to null (Nothing in VB.NET) once you have finished with them?

I understand that in .NET it is essential to

15条回答
  •  一向
    一向 (楼主)
    2020-11-22 16:47

    Another reason to avoid setting objects to null when you are done with them is that it can actually keep them alive for longer.

    e.g.

    void foo()
    {
        var someType = new SomeType();
        someType.DoSomething();
        // someType is now eligible for garbage collection         
    
        // ... rest of method not using 'someType' ...
    }
    

    will allow the object referred by someType to be GC'd after the call to "DoSomething" but

    void foo()
    {
        var someType = new SomeType();
        someType.DoSomething();
        // someType is NOT eligible for garbage collection yet
        // because that variable is used at the end of the method         
    
        // ... rest of method not using 'someType' ...
        someType = null;
    }
    

    may sometimes keep the object alive until the end of the method. The JIT will usually optimized away the assignment to null, so both bits of code end up being the same.

提交回复
热议问题