Preprocessor Directives
In the examples you’ve seen so far, you’ve compiled your entire program whenever you compiled any of it. At times, however, you might want to compile only parts of your program—for example, depending on whether you are debugging or building your production code.
Before your code is compiled, another program called the preprocessor
runs and prepares your program for the compiler. The preprocessor
examines your code for special preprocessor directives, all of which
begin with the pound sign (#
). These directives
allow you to define identifiers and then test for their existence.
Defining Identifiers
#define
DEBUG
defines a
preprocessor identifier, DEBUG
. Although other
preprocessor directives can come anywhere in your code, identifiers
must be defined before any other code, including
using
statements.
Tip
C and C++ programmer take note: The C# preprocessor implements only a subset of the C++ preprocessor.
You can test whether DEBUG
has been defined with
the #if
statement. Thus, you can write:
#define DEBUG //... some normal code - not affected by preprocessor #if DEBUG // code to include if debugging #else // code to include if not debugging #endif //... some normal code - not affected by preprocessor
When the preprocessor runs, it sees the #define
statement and records the identifier DEBUG
. The
preprocessor skips over your normal C# code and then finds the
#if
-
#else
-
#endif
block.
The #if
statement tests for the identifier
DEBUG
, which does exist, and so ...
Get Programming C#, Third Edition 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.