In C#, you can write preprocessor directives to give special instructions to the compiler. Here I'll show you how to use the #if directive to compile alternative parts of your code. For a complete list of directives, see C# preprocessor directives.
The #if directive comes in handy when you want to compile different lines of code, depending on whether the application is in development or in production. A good example is creating the Eclipse application in standalone apps. In development, you want to automatically log in with a specific username and password. In production, you want the user to log in manually.
In Visual Studio, there are two build configurations you can choose: Debug or Release (for more information, see How to: Set debug and release configurations in Visual Studio). In the Debug configuration, the DEBUG symbol is defined. You can think of this as a flag that's turned on throughout your program. In the Release configuration, the DEBUG symbol is not defined.
Let's look at an example:
#if DEBUG app = Application.CreateApplication("admin", "admin"); #else app = Application.CreateApplication(null, null); #endif
The #if directive tests whether the DEBUG symbol has been defined. If true, it compiles the following lines until the #else directive. If false, it compiles the lines after the #else directive until the #endif directive.
Therefore, when you run your app in the Debug configuration, the Eclipse application will use a specific username and password. When you want to release your application to a production environment, compile it in the Release configuration. The application will prompt the user to enter his or her credentials—this happens when the username and password are null.
You may use the #if DEBUG instruction in other scenarios. For example, you may want to output debug statements to a file or the screen while debugging. You may also use it to define different values for constants that make sense for a development or a production environment (e.g., database connection string).
If you find yourself using #if DEBUG all over your code, consider using the ConditionalAttribute instead. See the blog post If You’re Using “#if DEBUG”, You’re Doing it Wrong.