IDisposable & Disposal Pattern
Dependency Injection (DI)
Why This Is Asked
Resource management separates senior .NET developers from juniors. Interviewers want to see that you understand why the GC alone is insufficient for unmanaged resources, and that you can implement the full Dispose pattern correctly including finalizer coordination.
Key Concepts
- The GC handles managed memory but cannot clean up unmanaged resources (file handles, DB connections, sockets)
IDisposable.Dispose()provides deterministic cleanup — release resources immediately, not “eventually”- The full pattern involves a
Dispose(bool disposing)method, a_disposedflag, and optional finalizer GC.SuppressFinalize(this)prevents double-cleanup and avoids promoting the object to a higher GC generationusingstatements/declarations guaranteeDispose()is called even if an exception is thrown