C#: should object variables be assigned to null?

前端 未结 8 996
别那么骄傲
别那么骄傲 2020-11-27 05:48

In C#, is it necessary to assign an object variable to null if you have finished using it, even when it will go out of scope anyway?

8条回答
  •  日久生厌
    2020-11-27 06:52

    What matters more IMO is to call Dispose on objects that implement IDisposable.

    Apart from that, assigning null to reference variables will just means that you are explicitly indicating end of scope - most of times, its just few instruction early (for example, local variables in method body) - with era of compiler/JIT optimizations, its quite possible that runtime would do the same, so you really don;t get anything out of it. In few cases, such as static variables etc (whose scope is application level), you should assign variable to null if you are done using it so that object will get garbage collected.

提交回复
热议问题