Memory Management & Garbage Collection
Prerequisites: Design patterns in C#
Like Java, the CLR's garbage collector automatically reclaims
objects no longer reachable — no manual free/delete. IDisposable
(seen via using in Level 2) is for unmanaged resources (file
handles, network sockets, database connections) that the garbage
collector doesn't know how to release on its own timeline.
class FileWrapper : IDisposable {
private FileStream _stream;
public FileWrapper(string path) {
_stream = File.OpenRead(path);
}
public void Dispose() {
_stream.Dispose(); // release the OS file handle promptly
}
}
using (var wrapper = new FileWrapper("data.txt")) {
// ...
} // Dispose() called automatically here
Common mistakes
- Relying on the garbage collector alone to close a file or
network connection "eventually" — it will, but not
predictably; implement
IDisposableand useusingfor anything holding a genuinely limited external resource.