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 ...

Get C# Cookbook now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.