Setting Objects to Null/Nothing after use in .NET

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

    Karl is absolutely correct, there is no need to set objects to null after use. If an object implements IDisposable, just make sure you call IDisposable.Dispose() when you're done with that object (wrapped in a try..finally, or, a using() block). But even if you don't remember to call Dispose(), the finaliser method on the object should be calling Dispose() for you.

    I thought this was a good treatment:

    Digging into IDisposable

    and this

    Understanding IDisposable

    There isn't any point in trying to second guess the GC and its management strategies because it's self tuning and opaque. There was a good discussion about the inner workings with Jeffrey Richter on Dot Net Rocks here: Jeffrey Richter on the Windows Memory Model and Richters book CLR via C# chapter 20 has a great treatment:

提交回复
热议问题