#if Preprocessor Directive in C#

By Santhosh N

This explains the Microsoft .Net C# preprocessor directive, #if, #else and #endif and its usage for Conditional Compilation in the C# Language by the developers.

The #if preprocessor directive in C# is used to compile the code conditionally based on the specified symbol.

For example, if you want to run a piece of code only while you are debugging the application but not while deployed to live site, you could actually check for the DEBUG symbol using #if directive and run your application to have two versions without any blocking or manipulating the code for debugging purposes.

Ex:
#if DEBUG
    // statements to run only while debugging
#endif

The #if directive should be having corresponding #endif directive to mark the end of if block.
To have conditional else you have got one more directive, #else to use for else case of the symbol checking in C#.

Ex:
#if DEBUG
    // statements to run only while debugging
#else
// statements to run only while NOT debugging
#endif

Related FAQs

This list out all the available preprocessor directives in Microsoft .Net C# Language which helps developers to conditionally compile the applications while coding.
This explains how to find the version of the Microsoft Excel that has been installed in the system.
This explains how to make C# windows Forms TextBox accept only numeric values.
This explains the location of the Strong Name Generator Tool, sn.exe in Microsoft .Net 4.0 version when Visual Studio 2010 is installed.
#if Preprocessor Directive in C#  (1220 Views)