How can I easily exclude certain lines of code from compilation?

Scattered throughout the software project I'm working on is a lot of lines of code that have been written for debugging and use. Before I compile my code, I want to choose whether to include these blocks of code in my compiler (which does not require navigation to comment on the code). How can i do this?

I am programming in C # and using Microsoft Visual Studio 2010.

+6
debugging c # visual-studio shortcuts
source share
7 answers

Add the [Conditional("DEBUG")] attribute to the methods that you want to execute only in your debug build. See here for more details.

+13
source share

I would suggest including your blocks in #ifdef SOMETHING and #endif , and then defining SOMETHING in your project settings when you want to include this block in your compiler.

+7
source share

You need preprocessor directives or conditional compilations. You can read about them here .

An example from this link:

 #define TEST using System; public class MyClass { public static void Main() { #if (TEST) Console.WriteLine("TEST is defined"); #else Console.WriteLine("TEST is not defined"); #endif } } 

Code is compiled only if TEST is defined at the top of the code. Many developers use #define DEBUG, so they can enable code debugging and delete it again by simply changing one line at the top.

+7
source share

Consider using the Debug class for conditional log, statement, etc. There are many advantages to this. You can select a log (or not) at runtime. They limit you to (mostly) non-behavior actions and fix some @STW (valid) issues. They allow you to use third-party logging tools.

+3
source share
+1
source share

If they are intended for debugging, then the only acceptable solution is to surround this code:

 #ifdef DEBUG #endif 

This ensures that the code is enabled during compilation in debug mode, but excluded in release mode.

+1
source share

You might want to consider migrating these debugging functions from classes, as your classes โ€œchange shapeโ€ between Debug and Release modes can be a real headache and can be difficult to diagnose problems.

You can create a separate debug assembly that contains all your debugging helpers, and then just make sure that you can exclude it from the solution and build it successfully without it.

+1
source share

All Articles