Scattered throughout a software project I am working on are many lines of code that were written for debugging and utility purposes. Before I compile my code, I want a way to select whether or not these blocks of code should be included into my compile (something that won't require navigating the code commenting out). How can I do this?

I'm programming in c# and using Microsoft Visual Studio 2010.

+7  A: 

I would suggest enclosing your blocks in #ifdef SOMETHING and #endif, and then defining SOMETHING in your project settings when you want to include that block in your compile.

+6  A: 

You need preprocessor directives, or conditional compile statements. You can read about them here.

An example from that link:

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

The code is only compiled if TEST is defined at the top of the code. A lot of developers use #define DEBUG so they can enable debugging code and remove it again just by altering that one line at the top.

If you use build configurations in Visual Studio, the Debug build configuration (by default) defines DEBUG, and the Release build configuration does not. No need to define them manually.
+1  A: 

You can use preprocessor directives w/ #if

+1  A: 

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

#ifdef DEBUG


This ensures that the code is included when you compile in debug mode but excluded in release mode.

There are most certainly other acceptable solutions. The conditional attribute does the same thing, and (to me at least) would be preferable to directives, since in my experience, directives tend to mess with third party code analysis tools.
+1  A: 

You may want to consider moving these debugging functions out of the classes entirely--having your classes "change shape" between Debug and Release mode can be a real headache and can be difficult to diagnose problems.

You could consider creating a seperate "Debug" assembly which contains all your debugging helpers--then just make sure you can exclude it from the solution and build successfully without it.

+7  A: 

Pop [Conditional("DEBUG")] onto methods you only want to have execute in your debug build. See here for more detailed information.

Jesse C. Slicer
+1. IMVHO, this is the *cleanest* way.
I wasn't familiar with this conditional debug attribute, very slick.
Same - hadn't heard of this. Nice!
+3  A: 

Consider using the Debug class to conditionally log, assert, etc. There are many advantages to this. You can choose to log (or not) at runtime. They limit you to (mostly) non-behavior-changing actions, addressing some of @STW's (valid) concern. They allow the use of third-party logging tools.

Craig Stuntz