Alex Rivera | Logout

Segregating Debug and Release Code in C#

Asked 2010-07-22T17:03:34.433
11

I'm writing an application wherein I have some debug code that I do not wish to delete, but I wish it to be modified or removed when compiling for release/publish. For example, I would like something like this in a debug build:

MessageBox.Show(ex.ToString(), "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);

...to become this in a release build:

MessageBox.Show(ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);

Ideally, I was hoping to do something like this:

#if DEBUG_BUILD
   MessageBox.Show(ex.ToString(), "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
#else
   MessageBox.Show(ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
#endif

I would prefer to not have to add/remove a Conditional Compilation Symbol in the project properties every time I change the build type; it should happen automatically. Is there a way to do this in Microsoft Visual C# 2008 Express Edition? Thanks.

Edit
Report

1 Answer

13

You can also use this attribute.

[Conditional("DEBUG")]

This has a couple of advantages over the preprocessor directive.

All calls to methods marked conditional will be replaced with Nops if the conditional symbol isn't defined, which saves you having to modify all calls to it.

Your code will checked for errors even when the symbol is not defined. (Unlike when using #if DEBUG, which ignores the code in #else during compilation)

answered 2010-07-22T17:13:53.283

Your Answer