C# Compiler Directives
# and gives an instruction to the compiler rather than describing what the program does. Directives decide which code is compiled (#if), shape the warnings you get (#pragma, #nullable, #warning), and organise the file in the editor (#region). Unlike C and C++, C# has no macros and no #include: a symbol is only ever defined or undefined, so directives cannot rewrite your code behind your back.
How Directives Work
The rules are short:
- A directive occupies a whole line. Only whitespace may come before the
#, and only a//comment may follow the directive. - Directives are processed while the compiler reads the source, before types and methods are analysed. Code excluded by
#ifis not compiled at all, so it may even contain syntax errors. #defineand#undefmust appear before the first token of real code in the file, and they affect only that file. Project-wide symbols are set in the.csproj.
Predefined Symbols
The .NET SDK defines symbols for you, so most projects never need #define:
| Symbol | Defined when |
|---|---|
DEBUG | building the Debug configuration (the default for dotnet run and dotnet build) |
RELEASE | building with -c Release |
TRACE | both configurations, by default |
NET8_0, NET8_0_OR_GREATER | targeting .NET 8 (and similar symbols for every target framework) |
WINDOWS, ANDROID, IOS… | the target framework names an operating system, e.g. net8.0-windows |
Conditional Compilation
#if, #elif, #else and #endif include a block only when a condition on symbols is true. Conditions can combine symbols with &&, ||, ! and parentheses. Typical uses are extra diagnostics in Debug builds and code that must compile for several target frameworks.
For a whole method that should exist only in some builds, the [Conditional("DEBUG")] attribute is usually cleaner than #if: the method is always compiled and type-checked, but the compiler removes every call to it when the symbol is not defined.
// #define must come before any code; DEBUG and NET8_0_OR_GREATER come from the SDK.
#define VERBOSE
using System.Diagnostics;
Diag.Log("starting");
#if VERBOSE
Console.WriteLine("verbose mode is on");
#endif
#if DEBUG
Console.WriteLine("Debug build");
#elif RELEASE
Console.WriteLine("Release build");
#endif
#if NET8_0_OR_GREATER
Console.WriteLine(".NET 8 or newer");
#endif
Diag.Trace("only in Debug builds");
Console.WriteLine("done");
static class Diag
{
public static void Log(string message) => Console.WriteLine($"[log] {message}");
[Conditional("DEBUG")] // calls vanish from Release builds
public static void Trace(string message) => Console.WriteLine($"[trace] {message}");
}
Output of dotnet run:
[log] starting
verbose mode is on
Debug build
.NET 8 or newer
[trace] only in Debug builds
done
With dotnet run -c Release, the fourth line becomes Release build and the [trace] line disappears.
Symbols and Settings in the Project File
Directives in a file are for local exceptions. Anything that should apply to the whole project belongs in the .csproj, where reviewers will see it:
<PropertyGroup>
<TargetFramework>net8.0</TargetFramework>
<!-- add a symbol for every file, keeping the SDK's own symbols -->
<DefineConstants>$(DefineConstants);FEATURE_EXPORT</DefineConstants>
<!-- nullable reference types on for the whole project -->
<Nullable>enable</Nullable>
<!-- fail the build on warnings, except missing XML docs -->
<TreatWarningsAsErrors>true</TreatWarningsAsErrors>
<NoWarn>$(NoWarn);CS1591</NoWarn>
</PropertyGroup>
You can also define a symbol for a single build: dotnet build -p:DefineConstants=FEATURE_EXPORT (this replaces the defaults instead of adding to them).
Diagnostics and Regions
#warning and #error
#warning makes the compiler print your message as a warning; #error stops the build with your message. Combined with #if, #error guards against unsupported build configurations.
#if !NET8_0_OR_GREATER
#error This library requires .NET 8 or later.
#endif
#warning The export module is experimental
Console.WriteLine("built anyway");
Building this file prints warning CS1030: #warning: 'The export module is experimental' and the program still runs. Do not use #warning as a to-do list, though: warnings that never go away train everyone to ignore warnings. Use your issue tracker for that.
#region
#region Name … #endregion marks a block the editor can fold. It has no effect on the compiled program. Regions help in long generated files, but in hand-written code they often hide a class that has grown too big; splitting the class, or using a partial class across files, usually serves readers better.
class ReportBuilder
{
#region Formatting helpers
static string Header(string title) => $"== {title} ==";
static string Line(string text) => $"- {text}";
#endregion
}
#line
#line changes the line numbers and file name the compiler reports, and #line hidden hides lines from the debugger. It exists for tools that generate C# from another file — Razor pages and source generators use it so errors point to your source rather than the generated code. You will rarely write it by hand.
Nullable Context
Since C# 8, the compiler can track which reference variables may be null. In an enabled nullable context, string means "never null" and string? means "may be null"; the compiler warns when you dereference a string? without checking it, or assign null to a string. New projects enable it in the .csproj (<Nullable>enable</Nullable>). The #nullable directive overrides that setting for part of a file, which is how large old code bases migrate one file at a time.
#nullable enable, disable and restore
#nullable enable— annotations and warnings on from this line.#nullable disable— both off: the "oblivious" pre-C# 8 behaviour.#nullable restore— back to the project setting.#nullable enable warnings/annotations— switch only one half.
The postfix ! operator ("null-forgiving") tells the compiler that you know a value is not null. It removes the warning and nothing else: if you are wrong, you still get a NullReferenceException at run time.
// Nullable annotations are compile-time checks; they do not change run-time behaviour.
#nullable enable
string? FindUser(int id) => id == 1 ? "Ada" : null;
string? user = FindUser(2);
// Console.WriteLine(user.Length); // warning CS8602: possibly null
Console.WriteLine(user?.Length ?? 0); // safe: null-conditional + default
if (user is not null)
Console.WriteLine(user.Length); // no warning: the compiler saw the check
string name = FindUser(1)!; // "trust me": suppresses the warning only
Console.WriteLine(name.ToUpper());
#nullable disable
string legacy = null; // no warning: annotations are off here
Console.WriteLine(legacy ?? "(null)");
#nullable restore
Output:
0
ADA
(null)
#pragma warning
Disabling Specific Warnings
#pragma warning disable CS0618 silences the listed warnings until a matching #pragma warning restore. Keep the disabled region as small as possible, always name the warning number (a bare disable silences everything), and add a comment explaining why the warning does not apply. For a rule you disagree with across the whole project, change its severity in .editorconfig (dotnet_diagnostic.CA1822.severity = none) or in <NoWarn> instead.
// Calling an obsolete API on purpose, with the warning disabled only around the call.
#pragma warning disable CS0618 // OldApi.Run is obsolete, but the new API is not deployed yet
OldApi.Run();
#pragma warning restore CS0618
NewApi.Run();
static class OldApi
{
[Obsolete("Use NewApi.Run instead")]
public static void Run() => Console.WriteLine("old api");
}
static class NewApi
{
public static void Run() => Console.WriteLine("new api");
}
Output:
old api
new api
File-Based Apps (.NET 10)
#: Directives
.NET 10 can run a single .cs file without a project: dotnet run hello.cs. Such a file uses a newer kind of directive, starting with #:, to say what a .csproj would normally say — for example #:package Humanizer@2.14.1 to reference a NuGet package, #:sdk to choose an SDK and #:property to set an MSBuild property. On Linux and macOS a first line #!/usr/bin/env dotnet makes the file directly executable. These directives are ignored in normal projects; the feature is new, so check the .NET 10 SDK documentation on Microsoft Learn (listed in References) before relying on the details.
Practice
Directive Summary
| Directive | Purpose |
|---|---|
#define / #undef | define or remove a symbol in this file |
#if / #elif / #else / #endif | conditional compilation |
#warning / #error | custom compiler warning or error |
#region / #endregion | foldable block in the editor |
#line | adjust reported line numbers (generated code) |
#nullable | nullable reference type context |
#pragma warning | disable or restore specific warnings |
#: and #! | file-based app settings and shebang (.NET 10) |
Exercises
- Run the conditional compilation example in Debug and then with
-c Release, and confirm which lines change. - Add
<DefineConstants>$(DefineConstants);VERBOSE</DefineConstants>to the project, remove the#defineline, and check that the output stays the same. - Uncomment the
user.Lengthline in the nullable example and read the warning; then make the project treat that warning as an error. - Find a warning in one of your own projects and decide whether to fix it, suppress it with a narrow
#pragma, or change its severity in.editorconfig.