C# Compiler Directives
Directives start with
# and are processed before compilation. They control conditional compilation, collapsible regions, warnings, and the nullable context.
Preprocessor
Conditional Compilation
#if / #else / #endif include or exclude code based on symbols such as DEBUG.
#define LOCAL
#if LOCAL
Console.WriteLine("local build");
#else
Console.WriteLine("release build");
#endif
Region
#region groups code into a collapsible block in the editor.
#region Helpers
static int Triple(int x) => x * 3;
#endregion
Warning & Error
#warning emits a compiler warning; #error stops the build.
#warning This module is experimental
// #error remove me before release
Nullable Context
Enable
#nullable enable turns on nullable reference warnings. A ? suffix means the value may be null.
#nullable enable
string? maybe = null; // allowed, compiler warns on unsafe use
string required = "set";
Disable
#nullable disable turns the context off for the rest of the file.
#nullable disable
string legacy = null; // no warning in this scope
Pragma
Suppress Warnings
#pragma warning disable / restore silences specific warning numbers around a code block.
#pragma warning disable CS0168 // variable declared but never used
int unused;
#pragma warning restore CS0168