C# #define Preprocessor

In this chapter you will learn:

  1. What is Preprocessing Directives #define
  2. How to use Preprocessing Directives #define
  3. Example for Preprocessing Directives #define
  4. Use the Conditional attribute with #define

Description

The #define directive defines a character sequence called a symbol. The existence or nonexistence of a symbol can be determined by #if or #elif.

Syntax

The general form for #define:

#define symbol

Example

Example,


#define DEBUGLOG/*w  w w. j  a v  a 2  s .c  o  m*/

using System;

class MainClass
{
    public static void Main()
    {
        #if DEBUGLOG
        Console.WriteLine("In Main - Debug Enabled");
        #else
        Console.WriteLine("In Main - No Debug");
        #endif
    }
}

The code above generates the following result.

Example 2

Use the Conditional attribute with #define


#define USE_METHOD_1/*  w  ww  .  j  a  va 2  s  . c om*/

using System;
using System.Diagnostics;

class MainClass
{

  [Conditional("USE_METHOD_1")]
  public static void Method1()
  {
    Console.WriteLine("In Method 1");
  }

  public static void Main() 
  {
      Console.WriteLine("In Main");
    Method1();
  }
}

The code above generates the following result.

Next chapter...

What you will learn in the next chapter:

  1. How to use Preprocessing Directives #if
  2. Syntax for #if Preprocessing Directive
  3. Example for #if Preprocessing Directive
  4. Use #if with #else
Home »
  C# Tutorial »
    C# Types »
      C# Preprocessor
C# preprocessor
C# #define Preprocessor
C# #if Preprocessing Directive
C# #elif Preprocessing Directive
C# #undef
C# #line directive
C# #region directive
C# #warning preprocessor