I write some WinForm user controls that take up a fairly large number of drawings and therefore tend to have many one-time graphic fields lying around (Brushes, Pens, Bitmaps, etc.), and as a result, my control should call Dispose () method Dispose on each of them.
I was worried that I (or the future maintainer) could easily skip the field that needs to be removed, either forgetting to remove it, or not realizing that it implements IDisposable. Thus, I wrote a very simple extension method for Object, which finds and disposes of all IDisposable fields:
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 basically is whether it is wise to do this. I canβt think that this can ruin, but then Iβm not very familiar with the internal development of WinForms, and it looks like what is happening (messing with reflection and deletion), which can cause annoying errors in the queue.
source share