Conditional Compilation in C#: #if, #define and DEBUG

Conditional compilation directives decide at build time which parts of a source file the compiler sees. Code in an inactive #if block is not compiled at all: it produces no IL, and it does not even have to compile. Typical uses are debug-only diagnostics, code for a specific target framework or operating system, and feature switches.

#if DEBUG
Console.WriteLine("Debug build: verbose logging enabled");
#else
Console.WriteLine("Release build");
#endif

DEBUG is defined by the SDK in the Debug configuration, so this prints the first line with dotnet run and the second with dotnet run -c Release. TRACE is defined in both configurations.

Defining your own symbols

A #define at the top of a file creates a symbol for that file only; #undef removes one:

#define VERBOSE_LOGGING
#undef TRACE

using System.Diagnostics;

#if VERBOSE_LOGGING
Console.WriteLine("Verbose logging is on");
#endif

#if TRACE
Console.WriteLine("This line is not compiled, TRACE was undefined above");
#endif

Two rules trip people up. #define and #undef must come before anything else in the file, including using directives; otherwise the build fails with error CS1032. And symbols are case-sensitive: the original version of this example defined Debug, which is a different symbol from the built-in DEBUG.

A symbol that is meant for the whole project belongs in the project file:

<PropertyGroup>
  <DefineConstants>$(DefineConstants);VERBOSE_LOGGING</DefineConstants>
</PropertyGroup>

Keep the $(DefineConstants); prefix. Without it you replace the SDK’s symbols, and DEBUG, TRACE and the framework symbols below are gone. To set a symbol from the command line for one build, use dotnet build -p:DefineConstants=VERBOSE_LOGGING, which replaces the list in the same way.

Conditions, #elif and operators

Conditions can combine symbols with &&, ||, ! and parentheses, and test them with == true or == false:

#if DEBUG && !VERBOSE_LOGGING
    // Debug build without verbose logging
#elif DEBUG
    // Debug build with verbose logging
#else
    // Release build
#endif

An undefined symbol simply counts as false; there is no error for a typo, which is another reason to keep custom symbols few and spelled consistently.

Target framework symbols

The SDK defines a symbol for every target framework, which is what makes multi-targeted libraries possible. In a project with <TargetFrameworks>net8.0;netstandard2.0</TargetFrameworks>:

using System.Security.Cryptography;
using System.Text;

public static class Hashing
{
    public static string Sha256Hex(string input)
    {
        byte[] bytes = Encoding.UTF8.GetBytes(input);

#if NET5_0_OR_GREATER
        return Convert.ToHexString(SHA256.HashData(bytes));
#else
        using var sha = SHA256.Create();
        return BitConverter.ToString(sha.ComputeHash(bytes)).Replace("-", "");
#endif
    }
}

The most useful symbols:

SymbolDefined when targeting
NET.NET 5 and later
NET8_0exactly .NET 8
NET8_0_OR_GREATER.NET 8 and later (also NET6_0_OR_GREATER and so on)
NETFRAMEWORKany .NET Framework version, such as NET48
NETSTANDARD2_0.NET Standard 2.0
WINDOWSan OS-specific framework such as net8.0-windows

Prefer the _OR_GREATER form. #if NET8_0 silently stops matching when you move the project to .NET 9 or 10.

using var needs C# 8, which is not the default for netstandard2.0. Either set <LangVersion>latest</LangVersion> in the project, or use the older using (var sha = SHA256.Create()) { ... } block.

Often better: the [Conditional] attribute

For debug-only helper calls, System.Diagnostics.ConditionalAttribute is usually cleaner than wrapping every call in #if:

using System.Diagnostics;

public static class DevLog
{
    [Conditional("DEBUG")]
    public static void Write(string message) =>
        Console.WriteLine($"[debug] {message}");
}

The method itself is always compiled, so it cannot rot. Every call to DevLog.Write(...) is removed by the compiler when the calling code is built without DEBUG, including the evaluation of its arguments, so an expensive string built in the argument costs nothing in Release. The method must return void. Debug.WriteLine and Debug.Assert work this way.

Note that the decision is made where the call is compiled, not where the method is defined. A library compiled in Release that calls its own [Conditional("DEBUG")] method has those calls removed, no matter how your application is built.

Keep #if blocks small

Code inside an inactive branch is not compiled, so it is not checked either. Rename a method and the build stays green while the Release-only branch still calls the old name, until someone builds Release. Build every configuration in CI, keep the blocks short, and when the decision does not need to be made at compile time, use a runtime setting from configuration instead: it can be changed without a rebuild and both paths get compiled.

Related examples

Leave a Comment