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");

Drop a brain bomb

Please log in using one of these methods to post your comment: Logo

You are commenting using your account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s