0 day streak
csharp / intermediate
Snippet

Implementing the Standard Disposal Pattern

The IDisposable pattern is a fundamental pattern for managing memory and unmanaged resources. It ensures that resources are released deterministically rather than waiting for the Garbage Collector (GC).

snippet.cs
csharp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
public class ResourceHandler : IDisposable
{
private bool _disposed = false;
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
protected virtual void Dispose(bool disposing)
{
if (_disposed) return;
if (disposing)
{
// Free managed objects here
}
_disposed = true;
}
}
Breakdown
1
IDisposable
The interface used to provide a mechanism for releasing unmanaged resources.
2
GC.SuppressFinalize(this)
Informs the GC that the object's finalizer does not need to run because cleanup happened.
3
protected virtual void Dispose(bool disposing)
A protected method that allows subclasses to provide their own cleanup logic.