C#: should object variables be assigned to null?

2019-01-06 17:12发布

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?

7条回答
smile是对你的礼貌
2楼-- · 2019-01-06 17:44

Most of these responses have the right answer, but for the wrong reasons.

If it's a local variable, the variable will fall off the stack at the end of the method and therefore the object it was pointing to will have one less reference. If that variable was the only reference to the object, then the object is available for GC.

If you set the variable to null (and many who do were taught to do it at the end of the method) then you could actually wind up extending the time the object stays in memory because the CLR will believe that the object can't be collected until the end of the method because it sees a code reference to the object way down there. However, if you omit the setting of null the CLR can determine that no more calls for the object appear after a certain point in your code and, even though the method hasn't completed yet, the GC can collect the object.

查看更多
登录 后发表回答