Q:

C# program to demonstrate the conditional attribute using #define

0

C# program to demonstrate the conditional attribute using #define

All Answers

need an explanation for this answer? contact us directly to get an explanation for this answer

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.

 

need an explanation for this answer? contact us directly to get an explanation for this answer

total answers (1)

Similar questions


need a help?


find thousands of online teachers now