Setting Objects to Null/Nothing after use in .NET

后端 未结 15 2326
囚心锁ツ
囚心锁ツ 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:03

    In general, there's no need to null objects after use, but in some cases I find it's a good practice.

    If an object implements IDisposable and is stored in a field, I think it's good to null it, just to avoid using the disposed object. The bugs of the following sort can be painful:

    this.myField.Dispose();
    // ... at some later time
    this.myField.DoSomething();
    

    It's good to null the field after disposing it, and get a NullPtrEx right at the line where the field is used again. Otherwise, you might run into some cryptic bug down the line (depending on exactly what DoSomething does).

提交回复
热议问题