Why I Don’t Loop Through Dispose

Quite often graphical classes have a lot of disposing to do, e.g.:

public void Dispose() {


One might be tempted to optimize that a bit:

public void Dispose() {
foreach(IDisposable element in new IDisposable[] { foreBrush, backBrush, someBrush, }) {

I personally find this code a bit easier to maintain and it serves same purpose. But I never really use it due to one serious drawback - it is not recognized by code analysis.

Code analysis that is part of Visual Studio Professional (and higher) does not recognize operation of this loop and thus it reports CA2213: Disposable fields should be disposed violation. While it is clear that violation is invalid, it still means that our loop goes completely unchecked.

If we add one more disposable field to class at some future time, first scenario would give us notice and we would be aware of forgotten dispose. After quick check we add dispose of that field and all is nice.

In second case we have taken responsibility of disposal ourselves and Visual Studio is not capable of checking the loop. There is nobody to check that all fields are disposed and if we forget to dispose it, it will be up to garbage collection to do it.

This will usually not be a major issue because resources will be released at some time. If we take some OS resource (e.g. file handle) it might be a bit annoying for rest of system but again nothing critical.

However, under rare circumstances, it might become important. Call me lazy, but I would rather have a bit uglier code that is automatically validated than have beautiful code that I need to check myself.

Leave a Reply

Your email address will not be published. Required fields are marked *