Be careful with Debug.Assert

What is wrong with this code?

Debug.Assert(Marshal.ReleaseComObject(this.decoder) == 0, "Ensure it's released properly");

I foolishly wrote this line of code only to find (luckily) that FxCop was telling that the private field decoder was never referenced. How could that be I thought? The “Find All References” command yields this line in its results, it must be a bug I thought.

Of course after thinking about it for a second I realized that I was running FxCop against the Release version of my assembly, then I remembered that the method Debug.Assert has the Conditional attribute on it so that it doesn’t get compiled in release mode, doh!

The ConditionalAttribute actually allows you to tell the compiler that calls to this method are to be completely ignored unless the current configuration matches the parameter. It’s very handy but also very tricky! Be sure that there are no side effects in your assert expression.

Here is the modified version of the code.

int refrernceCount = Marshal.ReleaseComObject(this.decoder);
Debug.Assert(refrernceCount == 0, "Ensure it's released properly");

Author: justinmchase

I'm a Software Developer from Minnesota.

Leave a Reply

%d bloggers like this: