How to use #error and #warning directives in C#?

CsharpProgrammingServer Side Programming

#error directive

The #error directive allows generating an error from a specific location in your code.

Let us see an example −

Example

 Live Demo

using System;

namespace Demo {
   class Program {
      public static void Main(string[] args) {
         #if (!ONE)
         #error ONE is undefined
         #endif
         Console.WriteLine("Generating a user-defined error!");
      }
   }
}

After running the above program, a user-defined error generates −

Output

Compilation failed: 1 error(s), 0 warnings
error CS1029: #error: 'ONE is undefined'

#warning directive

The #warning directive allows generating a level one warning from a specific location in your code.

Let us see an example −

Example

 Live Demo

using System;

namespace Demo {
   class Program {
      public static void Main(string[] args) {
         #if (!TWO)
         #warning TWO is undefined
         #endif
         Console.WriteLine("Generates a warning!");
      }
   }
}

After running the above program, warning generates and the output is visible −

Output

warning CS1030: #warning: `TWO is undefined'
Generates a warning!
raja
Updated on 20-Jun-2020 15:08:10

Advertisements