Can you tag a section of code that will only be included in the Debug build?

Sorry for the extreme newbie question, but I haven't been able to find an answer elsewhere and have never actually done anything like this (I guess this happens when your company uses a production environment for testing).

It would be nice if Visual Studio could provide some mechanism for specifying that certain code segments (such as logging) should only be included in the Debug assembly. Does it exist? I'm interested in methods to do this in both C # and VB.NET, and VS 2005 if that matters.

+2


source to share


2 answers


There are several ways.

To mark a specific section of your code only for inclusion in Debug assemblies, you can do this in C #:

#if DEBUG
    code that will only compile for Debug
#endif

      

If you want to avoid this, you can mark the methods with an attribute:



[Conditional("DEBUG")]
public void Log(String message) { ... }

      

In this case, calls to this method will be automatically removed from your compiled code unless you compile for Debug. There are restrictions on this. For example, if you use parameters ref

or out

or return values, you cannot use that.

You can read more about the #if directive here: C # preprocessor directives and attribute here: ConditionalAttribute .

+7


source


We do this in AssemblyInfo.cs:

#if DEBUG
  [assembly: AssemblyConfiguration ("Debug")]
#else
  [assembly: AssemblyConfiguration ("Release")]
#endif


So this works for C #.

+1


source







All Articles