ADVERTISEMENT
ADVERTISEMENT

C# program to demonstrate the conditional attribute using #define

Here, we are going to demonstrate the conditional attribute using #define in C#?
Submitted by Nidhi, on October 31, 2020

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

Program:

The source code to demonstrate the 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 »


ADVERTISEMENT



ADVERTISEMENT



Comments and Discussions


ADVERTISEMENT

ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT

Languages: » C » C++ » C++ STL » Java » Data Structure » C#.Net » Android » Kotlin » SQL
Web Technologies: » PHP » Python » JavaScript » CSS » Ajax » Node.js » Web programming/HTML
Solved programs: » C » C++ » DS » Java » C#
Aptitude que. & ans.: » C » C++ » Java » DBMS
Interview que. & ans.: » C » Embedded C » Java » SEO » HR
CS Subjects: » CS Basics » O.S. » Networks » DBMS » Embedded Systems » Cloud Computing
» Machine learning » CS Organizations » Linux » DOS
More: » Articles » Puzzles » News/Updates

© https://www.includehelp.com some rights reserved.