C# .NET Resources – How to Find Out What Resources Are Unmanaged?

cgarbage-collectionnetresources

Looking through the .NET documentation, specifically the WebRequest class, I don't see any information indicating that I should wrap an instantiation of it in a using statement. Even the provided example does not do this. In most examples online however, this is exactly what's done.

My question is then, how do I know specifically which classes need to be disposed? Is there a general rule of thumb or do you inspect class definitions to see if they somehow handle unmanaged resources?

Best Answer

My question is then, how do I know specifically which classes need to be disposed?

Does it implement IDisposable? Yes? Then it needs to be disposed. If not, not. You can maybe get away without it in some apps (C# and modern operating systems in general are better about cleaning up after you), but it is still wrong®.

There are a very few framework classes that need Close (or something similar) called instead, and do not implement IDisposable, but these will say so in their documentation. These though are exceptions.

Related Topic