Preprocessor directives are instructions that we give to the compiler and compilers job is to compile code based on those instructions.

All preprocessor directives must begin with hash(#) sign, but do not need to end with semicolon(;) because they are not statements.

Preprocessor directives are not inherited and are file specific.

List of preprocessor directives:

#define
#undef
#if
#else
#elif
#endif
#warning
#error
#line
#region
#endregion
#pragma
#pragma warning
#pragma checksum

#define

Define directive followed by its uppercase name is used to define a directive. Put it always at the top of a file. By using define directive you ensure that if other directives are looking for it their result will be true.

#undef

At some point in code you will want to undefine specific directive, or to disable it, that is where you use undef directive. It can be located  anywhere in your code.

#if,  #else, #elif, #endif

You are certainly familiar with most of those keywords and the perform operations that you would expect of them to  do. Available operators are: ==,  !=, &&, || and !. You use operators ==,  != to check if directive exist, and you should always end with wndif directive.

#warning

warning lets you generate a level one warning from a specific location in your code. If conditions are true warning will be displayed inside ErrorList screen

Preprocessor Directives

Warning preprocessor directive

#error

error lets you generate an error from a specific location in your code. Note that your code will not build.

Preprocessor Directives

Warning preprocessor directive

#line

line lets you modify the compiler’s line number and (optionally) the file name output for errors and warnings. These information may or may not be true it really depend on what you wan to do.

#line hidden. Debugger will ignore this line but will  process it anyway.

#line numberOfLine fileName. ErrorList screen will display file name and line number you speccified here. Actually if error occurs 10 lines after this directive is declared it will show line 10.

#line default. Negates #line hidden. Meaning that if at any point you use # line default all hidden lines will be shown.

Preprocessor Directives

Warning preprocessor directive

#region and #endregion

These two directives are here to help you organize code more efficiently. You will use them if class where you are working from has grown too big. What they allow you is to wrap them around code, so you can expand or collapse it in Visual Studio or in any other smarter source code editor like Notepad++.  You can nest multiple regions inside one region.

Lets create two regions, one for properties and another for methods. See How we have collapsed Methods region, now it takes 2 lines instead of 13 lines.

Preprocessor Directives

Region and Endregion preprocess directives