Industrial manufacturing
Industrial Internet of Things | Industrial materials | Equipment Maintenance and Repair | Industrial programming |
home  MfgRobots >> Industrial manufacturing >  >> Industrial programming >> C Language

Mastering C# Preprocessor Directives: A Practical Guide

Mastering C# Preprocessor Directives

Discover how C# preprocessor directives shape compilation, control flow, and error handling. This guide covers each directive, its syntax, real‑world examples, and best practices.

Preprocessor directives are commands that the compiler evaluates before actual compilation begins. They dictate which sections of code are included, how warnings and errors are handled, and can even modify the compiler’s view of line numbers and filenames.

In C#, a directive starts with a # symbol and spans a single line, terminated by a newline rather than a semicolon.

Preprocessor Directives in C#
DirectiveDescriptionSyntax
#ifEvaluates a preprocessor expression and includes code only if true.
#if expression
    code
#endif
#elifUsed after #if to test additional expressions.
#if expr1
    code1
#elif expr2
    code2
#endif
#elseRuns when none of the preceding #if or #elif conditions are true.
#if expr1
    code1
#else
    code2
#endif
#endifMarks the end of a conditional block.
#if expr
    code
#endif
#defineDefines a new symbol.
#define SYMBOL
#undefRemoves a previously defined symbol.
#undef SYMBOL
#warningGenerates a level‑1 compiler warning.
#warning Your warning message
#errorCauses a compile‑time error.
#error Your error message
#lineOverrides the compiler’s line number and filename for diagnostics.
#line 50 "FakeProgram.cs"
#endif
#regionCreates a collapsible region in editors like Visual Studio.
#region Description
    code
#endregion
#pragmaPasses special instructions to the compiler (e.g., enable/disable warnings).
#pragma warning disable
#endif

Defining and Undefining Symbols

Example: Defining a Symbol

#define TESTING

Example: Undefining a Symbol

#undef TESTING

Conditional Compilation with #if, #elif, #else, and #endif

Practical Example

#define CSHARP
#undef PYTHON

using System;

namespace Directive
{
    class ConditionalDirective
    {
        static void Main(string[] args)
        {
            #if (CSHARP && PYTHON)
                Console.WriteLine("CSHARP and PYTHON are defined");
            #elif (CSHARP && !PYTHON)
                Console.WriteLine("CSHARP is defined, PYTHON is undefined");
            #elif (!CSHARP && PYTHON)
                Console.WriteLine("PYTHON is defined, CSHARP is undefined");
            #else
                Console.WriteLine("CSHARP and PYTHON are undefined");
            #endif
        }
    }
}

Output: CSHARP is defined, PYTHON is undefined


Generating Warnings and Errors

Warning Example

using System;

namespace Directives
{
    class WarningDirective
    {
        public static void Main(string[] args)
        {
            #if (!CSHARP)
                #warning CSHARP is undefined
            #endif
            Console.WriteLine("#warning directive example");
        }
    }
}

Output includes a warning line but the console text prints.

Error Example

using System;

namespace Directive
{
    class Error
    {
        public static void Main(string[] args)
        {
            #if (!CSHARP)
                #error CSHARP is undefined
            #endif
            Console.WriteLine("#error directive example");
        }
    }
}

Output: build fails with a compile‑time error; the final console line is never executed.


Customizing Diagnostic Locations with #line

Example

using System;

namespace Directive
{
    class LineDemo
    {
        public static void Main(string[] args)
        {
            #line 200 "AnotherProgram.cs"
            #warning Actual warning generated by Program.cs on line 10
        }
    }
}

Result: Warning appears as AnotherProgram.cs(200,22): warning CS1030: ...


Organizing Code with #region and #endregion

Example

using System;

namespace Directive
{
    class RegionDemo
    {
        public static void Main(string[] args)
        {
            #region Hello
            Console.WriteLine("Hello");
            Console.WriteLine("Hello");
            Console.WriteLine("Hello");
            Console.WriteLine("Hello");
            Console.WriteLine("Hello");
            #endregion
        }
    }
}

Output: five lines of "Hello".


Advanced Compiler Instructions with #pragma

Example

using System;

namespace Directive
{
    class PragmaDemo
    {
        public static void Main(string[] args)
        {
            #pragma warning disable
            #warning This is a warning 1
            #pragma warning restore
            #warning This is a warning 2
        }
    }
}

Only the second warning is displayed.

For deeper insight, refer to the official #pragma (C# reference).



C Language

  1. Understanding C# Keywords and Identifiers: Rules, Lists, and Best Practices
  2. Understanding C++ Data Types: Fundamentals, Modifiers, and Best Practices
  3. C Keywords & Identifiers: A Practical Guide
  4. C Data Types Explained: int, float, char, and More – A Complete Guide
  5. C Preprocessor & Macros: Mastering #include, #define, and Conditional Compilation
  6. Mastering Python's strftime(): Convert Dates and Times to Readable Strings
  7. Master Python's strptime() for Accurate Date Parsing
  8. Understanding the C Preprocessor (CPP): How It Simplifies Compilation
  9. C++ Preprocessor: How Directives Shape Your Code
  10. Master C# Preprocessor Directives: How They Shape Your Code