I think this is a simple question so I assume I'm missing something obvious. I don't really ever use preprocessor directives but I was looking at someone's code which did and thought it was something I should be familiar with.
So I looked at the msdn example here it has the code:
#define DEBUG // ... #if DEBUG Console.WriteLine("Debug version"); #endif
My two questions are:
#define MYTEST
and then writes to the console dependent on if it 'defined', but how does this differ from just using a variable? What am I missing here?Preprocessor directives, such as #define and #ifdef , are typically used to make source programs easy to change and easy to compile in different execution environments. Directives in the source file tell the preprocessor to take specific actions.
The #define directive causes the compiler to substitute token-string for each occurrence of identifier in the source file. The identifier is replaced only when it forms a token. That is, identifier is not replaced if it appears in a comment, in a string, or as part of a longer identifier.
As the name justifies, preprocessor directives are a block of statements that gets processed before the actual compilation starts. C# preprocessor directives are the commands for the compiler that affects the compilation process.
#define lets you define a symbol. By using the symbol as the expression passed to the #if directive, the expression evaluates to true . You can also define a symbol with the DefineConstants compiler option. You can undefine a symbol with #undef .
I would actually recommend using the Conditional Attribute instead of inline #if statements.
[Conditional("DEBUG")] private void DeleteTempProcessFiles() { }
Not only is this cleaner and easier to read since you don't end up having #if, #else within your code. This style is less prone to errors either during normal code edits and well as logic flow errors.
Generally, the optional/conditional compilation symbols will be provided by the build script. It is pretty rare to see #define
, except for very debug code (if you see what I mean).
Re using a variable; I often use such conditions to handle code that must run on different runtimes (mono, cf, silverlight, etc). A variable cannot suffice because the code cannot be compiled against the wrong platform (missing types/methods etc).
In the example presented I would probably just have used Debug.WriteLine
; since this is decorated with [Conditional("DEBUG")]
, all calls to it are automatically removed if DEBUG
is not defined at build.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With