HomeAbout Me

C# PREPROCESSOR DIRECTIVES

By Daniel Nguyen
Published in WPF - CSharp
November 04, 2022
1 min read
C# PREPROCESSOR DIRECTIVES

The preprocessor directives give instruction to the compiler to preprocess the information before actual compilation starts.

All preprocessor directives begin with #, and only white-space characters may appear before a preprocessor directive on a line. Preprocessor directives are not statements, so they do not end with a semicolon (;).

Preprocessor Directives in C#

PropertyDescription
#defineIt defines a sequence of characters, called symbol.
#undefIt allows you to undefine a symbol.
#ifIt allows testing a symbol or symbols to see if they evaluate to true.
#elseIt allows to create a compound conditional directive, along with #if.
#elifIt allows creating a compound conditional directive.
#endifSpecifies the end of a conditional directive.
#lineIt lets you modify the compiler’s line number and (optionally) the file name output for errors and warnings.
#errorIt allows generating an error from a specific location in your code.
#warningIt allows generating a level one warning from a specific location in your code.
#regionIt lets you specify a block of code that you can expand or collapse when using the outlining feature of the Visual Studio Code Editor.
#endregionIt marks the end of a #region block.

The #define Preprocessor

The #define preprocessor directive creates symbolic constants.

#define lets you define a symbol such that, by using the symbol as the expression passed to the #if directive, the expression evaluates to true. Its syntax is as follows:

#define PI
using System;
namespace PreprocessorDAppl
{
class Program
{
static void Main(string[] args)
{
#if (PI)
Console.WriteLine("PI is defined");
#else
Console.WriteLine("PI is not defined");
#endif
Console.ReadKey();
//PI is defined
}
}
}

Conditional Directives

You can use the #if directive to create a conditional directive. Conditional directives are useful for testing a symbol or symbols to check if they evaluate to true. If they do evaluate to true, the compiler evaluates all the code between the #if and the next directive.

#define DEBUG
#define VC_V10
using System;
public class TestClass
{
public static void Main()
{
#if (DEBUG && !VC_V10)
Console.WriteLine("DEBUG is defined");
#elif (!DEBUG && VC_V10)
Console.WriteLine("VC_V10 is defined");
#elif (DEBUG && VC_V10)
Console.WriteLine("DEBUG and VC_V10 are defined");
#else
Console.WriteLine("DEBUG and VC_V10 are not defined");
#endif
Console.ReadKey();
//DEBUG and VC_V10 are defined
}
}

Tags

#CSharp

Share

Previous Article
C# INTERFACES

Table Of Contents

1
Preprocessor Directives in C#
2
The #define Preprocessor
3
Conditional Directives

Related Posts

C# ARRAYS
January 05, 2024
1 min
© 2025, All Rights Reserved.
Powered By

Quick Links

About Me

Legal Stuff

Social Media