Wow. A lot of questions here!
When SHOULD I use IDisposable? Only when I have unmanaged resources?
IDisposable
is usually used to clean up resources, but that's not necessarily all it's good for. It's a general pattern to notify the object being consumed that you're done with it. One example is a timer:
using(var timer = new MyTimer())
{
//do some stuff
}
In this case, calling Dispose
isn't necessarily releasing any resources, it's just a convenient & consistent (two keys for a pattern!) way to tell the timer "OK, I'm done with you now" and the timer can stop timing, and maybe record the time somewhere.
Another good rule of thumb is if you need to have a finalizer, for whatever reason, you should usually also provide IDisposable
access to the same routine so the consuming class can opt to finalize the class earlier instead of waiting on the GC.
What variations of the dispose pattern are there and why do they vary?
There is only one real "specific" type of IDisposable
implementation I'm aware of - the Finalize/Dispose pattern:
public class MyClass : IDisposable
{
void IDisposable.Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
protected virtual void Dispose(bool disposing)
{
if (disposing)
{
// Free other state (managed objects).
}
// Free your own state (unmanaged objects).
// Set large fields to null.
}
~MyClass()
{
Dispose(false);
}
}
What are common unmanaged resources I should be aware of?
Anything that implements IDisposable
, especially in the .NET libraries, should be assumed to have handles to unmanaged resources and should be disposed. Typically you'll only access unmanaged resources through these. If not, you'll know - usually building a driver or something.
Is it ever wrong or misleading to implement IDisposable?
It can be pointless to overuse it, but not directly harmful.
Should Dispose calls ever be chained together
A class should only dispose any IDisposables that it creates internally. If it has disposable dependencies that were injected or live beyond the scope of the class, you should never dispose them.