I've been writing some custom WinForm controls which do a pretty heavy amount of drawing and therefore tend to have a lot of disposable graphics based fields lying around (Brushes, Pens, Bitmaps etc..) and as a result my Control's Dispose() method has to call Dispose on each of them.
I got concerned that I (or a future maintainer) could easily miss a field that needs to be disposed, either by forgetting to Dispose it or by not realising that it implements IDisposable. As such I wrote a very simple extension method on Object which finds all the IDisposable fields and disposes of them:
static public void DisposeAll(this Object obj)
{
var disposable = obj.GetType()
.GetFields(BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.Instance)
.Select(fi => fi.GetValue(obj))
.Where(o => o != null && o is IDisposable)
.Cast<IDisposable>();
foreach (var d in disposable) d.Dispose();
}
My question is basically whether this is a reasonable thing to do. I can't think what it might screw up, but then I'm not particularly familiar with the inner workings of WinForms and this seems like the kind of thing (messing with reflection and disposing) that might cause irritating bugs down the line.