O'Reilly logo

C# Cookbook by Jay Hilyard, Stephen Teilhet

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

6.5. Conditionally Compiling Blocks of Code

Problem

Specific blocks of code will be used only in a nonrelease build of your application. These blocks of code should not be compiled into the release version of the application. You need a way to conditionally compile specific blocks of code based on the type of build.

Solution

There are two methods of allowing or preventing code from being compiled. The first is to use the C# preprocessor directives. The available preprocessor directives are:

#define
#undef
#if
#elif
#else
#endif

The #define and #undef preprocessor directives define and undefine symbols. These symbols are then used by the #if and #elif preprocessor directives to determine whether the blocks of code they wrap are to be compiled.

The second method of allowing or preventing code from being compiled is to use the ConditionalAttribute attribute to allow a method to be compiled based on a defined symbol. This attribute is used to specify a method as conditionally compiled as follows:

#define TRACE 

    ...

[ConditionalAttribute("TRACE")]
public void TraceHelp(string message)
{
    ...
}

The TraceHelp method is compiled only when the TRACE preprocessing identifier is defined.

Discussion

The ConditionalAttribute attribute can be used only on methods to prevent them from being compiled and called at runtime when the preprocessor identifier passed to the ConditionalAttribute attribute’s constructor is undefined. Properties, indexers, and other members cannot have this attribute.

Another ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required