In this lesson, you will learn how to use Conditional Compilation Symbols to instruct the C# compiler to include or exclude specific blocks of code depending on your build configuration.
Why do we need this?
Imagine you are building a game that runs on both Windows and a console. You might have code that interacts with Windows-specific hardware or, more commonly, you want to include extra "logging" or "debugging" features in your development build that shouldn't exist in the final version you send to customers. Instead of manually deleting code, you use conditional symbols.
The #if Directive
The C# compiler looks for special directives—starting with a #—to decide whether to "compile" the code inside them. If the symbol you specify is defined, the code is included; if not, the compiler acts as if that code doesn't exist at all.
#define DEBUG_MODE
public void LogStatus(string message)
{
#if DEBUG_MODE
// This code only exists if DEBUG_MODE is defined
Console.WriteLine($"[DEBUG]: {message}");
#else
// This code runs if DEBUG_MODE is NOT defined
Console.WriteLine("System running normally.");
#endif
}
How it works
- Define: You define symbols at the very top of your file (or via project settings).
- Evaluate: The preprocessor sees the
#ifdirective. - Compile: If the symbol matches, the code inside is compiled into your final assembly. If it doesn't, that code is completely ignored by the compiler, meaning it adds zero performance or size overhead to your executable.
This is a powerful way to manage multiple target platforms within a single codebase. If you are building for different environments, you can define symbols like WINDOWS or MOBILE in your project build settings, allowing you to swap out logic without changing your main program structure. This ensures your final app remains lightweight and secure by stripping out any "dev-only" tools before the code reaches the end user.
Key Takeaway: Conditional compilation symbols act as a "switch" for the compiler, allowing you to include or exclude specific code blocks from the final build without manual editing.