24.1. Conditional compilation With #define, #undef, #if and #endif

You use #define to declare a symbol. You can think of a symbol as a variable which is declared but not given a value. These symbols are used only by the C# compiler and have no effect at all on other parts of the source code.

Used in isolation, #define does not make sense but when used with #if and #endif, you can determine if blocks of source code, delimited by #if and #endif, will be included into your final IL codes after compilation. Here is an example:

 1: #define DEBUG
 2:
 3: using System;
						4:
						5: public class TestClass{
						6:
						7:   public static void Main(){
 8: #if DEBUG
						9:     Console.WriteLine("in Main");
10: #endif
						11:     Console.WriteLine("running statement");
						12:   }
						13: }
					

Output: ...

Get From Java to C#: A Developer's Guide 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.