C# - Conditional Attribute Using #define Preprocessor

In this example, we will learn how to implement conditional attribute using #define preprocessor using C# program?
Submitted by Nidhi, on October 31, 2020 [Last updated : March 22, 2023]

Here, we will demonstrate the exmample of conditional attribute using #define macro.

C# program to demonstrate the example of conditional attribute using #define

The source code to demonstrate the example of condition attribute using #define is given below. The given program is compiled and executed successfully on Microsoft Visual Studio.

//C# program to demonstrate the conditional 
//attribute using #define.

#define PRINT_MSG
using System;
using System.Diagnostics;

class Sample
{
   [Conditional("PRINT_MSG")]
   public static void PrintMessage() 
   {
      Console.WriteLine("Debug is enabled");
   }

   public static void SayHello()
   {
       PrintMessage();
       Console.WriteLine("Hello World");
   }
}

class Program
{
   public static void Main() 
   {
       Sample.SayHello();
   }
}

Output

Debug is enabled
Hello World
Press any key to continue . . . 

Explanation

In the above program, we created a #define macro "PRINT_MSG", Here we created a class Sample that contains two static methods. Here we used #define "PRINT_MSG" in condition attribute for PrintMessage(), If we use a conditional attribute with a method, then the execution of the method depends on #define constant. If we did not define #define macro then the method with conditional attribute will not execute.

Now look to the Program class, The program class contains the Main() method. The Main() method is the entry point for the program, Here we called the SayHello() method and the SayHello() method will call PrintMessage() method and print appropriate message on the console screen.

C# Basic Programs »

Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.