Setting Objects to Null/Nothing after use in .NET

后端 未结 15 2151
囚心锁ツ
囚心锁ツ 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 17:02

    Chances are that your code is not structured tightly enough if you feel the need to null variables.

    There are a number of ways to limit the scope of a variable:

    As mentioned by Steve Tranby

    using(SomeObject object = new SomeObject()) 
    {
      // do stuff with the object
    }
    // the object will be disposed of
    

    Similarly, you can simply use curly brackets:

    {
        // Declare the variable and use it
        SomeObject object = new SomeObject()
    }
    // The variable is no longer available
    

    I find that using curly brackets without any "heading" to really clean out the code and help make it more understandable.

提交回复
热议问题