The general pattern for this is to implement the IDisposable
interface on your class. Take this example:
public class YourClass : IDisposable
{
private OtherDisposableType yourResource;
public YourClass()
{
yourResource = new OtherDisposableType();
}
public void Dispose()
{
yourResource.Dispose();
}
}
This is, at a minimum, what you need to do.
EDIT
My previous version advocated following the finalizer pattern in all cases, which was (correctly) pointed out to be against the framework design guidelines. However, in the event that you're actually dealing with unmanaged resources (for example, you're making direct P/Invoke calls and obtaining a handle that needs to be explicitly freed) it's advisable that you create a finalizer and call Dispose
within it to protect against people who consume your code and don't call Dispose
:
public class YourClass : IDisposable
{
private OtherDisposableType yourResource;
public YourClass()
{
yourResource = new OtherDisposableType();
}
public void Dispose()
{
yourResource.Dispose();
GC.SuppressFinalize(this);
}
~YourClass()
{
Dispose();
}
}