Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Segregating Debug and Release Code in C#

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.

like image 522
Jim Fell Avatar asked Jul 22 '10 17:07

Jim Fell


People also ask

What is difference between Release and debug mode?

Debug Mode: In debug mode the application will be slow. Release Mode: In release mode the application will be faster. Debug Mode: In the debug mode code, which is under the debug, symbols will be executed. Release Mode: In release mode code, which is under the debug, symbols will not be executed.

What is Release with debug info?

RelWithDebugInfo means build with debug symbols, with or without optimizations. Anyway, the debug symbols can be stripped later, both using strip and/or obj-copy. If you use strip, the output can be saved.

Can we debug in Release mode in Visual Studio?

Visual Studio projects have separate release and debug configurations for your program. You build the debug version for debugging and the release version for the final release distribution. In debug configuration, your program compiles with full symbolic debug information and no optimization.


2 Answers

Use:

#if DEBUG
  // Debug work here
#else
  // Release work here
#endif

If you do that, just make sure to turn on the "Define DEBUG Constant" toggle in the property pages (Build page of the Project's properties), and it will work. This is set to true by default for new C# projects. DEBUG will get defined for you (by default) by the C# compiler.

like image 87
Reed Copsey Avatar answered Oct 05 '22 07:10

Reed Copsey


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)

like image 38
Mark H Avatar answered Oct 05 '22 07:10

Mark H