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


#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!

Samual Sam
Samual Sam

Learning faster. Every day.

Updated on: 20-Jun-2020

388 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements