Interview frequency: …
Short answer
The CLR manages Managed resources automatically, while Unmanaged resources (such as operating system file handles and network sockets) require explicit release through IDisposable and Dispose().
Explanation
The Garbage Collector does not know when or how to close an operating system file handle or database connection. Implementing IDisposable allows a using block (or using declaration) to guarantee that Dispose() is called as soon as execution leaves the scope. The advanced Dispose(bool disposing) pattern protects unmanaged resources with a Finalizer (~Class()) as a last resort if the developer forgets to call Dispose().
Code example
public class ResourceHolder : IDisposable {
private bool _disposed;
public void Dispose() {
Dispose(true);
GC.SuppressFinalize(this); // Suppress the Finalizer to save resources GC
}
protected virtual void Dispose(bool disposing) {
if (!_disposed) {
if (disposing) { /* Free managed resources */ }
/* Free unmanaged resources */
_disposed = true;
}
}
}Common mistakes
- Forgetting GC.SuppressFinalize(this) inside Dispose(), forcing the GC to keep the object through an unnecessary extra cleanup cycle.