csharp / intermediate
Snippet
Deterministic Resource Cleanup with IDisposable
The IDisposable interface is used to provide a mechanism for releasing unmanaged resources, such as file handles or database connections, which the Garbage Collector cannot handle automatically.
snippet.csharp
1
2
3
4
5
6
7
8
public class Logger : IDisposable{private StreamWriter _writer = new StreamWriter("log.txt");public void Dispose(){_writer?.Dispose();}}
Breakdown
1
IDisposable
An interface requiring the implementation of a single 'Dispose' method.
2
Dispose()
This method should contain logic to close or release all resources held by the object.