35

Using Attributes in C#

Share on TwitterShare on TumblrSubmit to StumbleUponSave on DeliciousDigg This

In this article I shall demonstrate how to use attributes in C#

Introduction

After finishing the Part 2, you decide to create a program that uses the attributes capabilities of C#.

Step 1 of 4
Some of the methods in your program will only run under certain conditions.
Enter the line of code that lets you define a symbol called “DEBUGGING”.
 
MISSING CODE
using System;
 
Result
The symbol is defined with the line #define DEBUGGING.
Step 2 of 4

You decide to use the Conditional intrinsic attribute to mark some methods that will only be used for debugging.
Type the name of the .NET namespace in which the Conditional attribute is defined.
 
#define DEBUGGING
using System;
using MISSING CODE;
using System.Runtime.InteropServices;
Result
You type System.Diagnostics. The Conditional attribute is defined in this namespace.
Step 3 of 4

The first method in this assembly will execute only when the program is debugging.
Enter the code that will tell the compiler that this code should only be run during debugging.
 
#define DEBUGGING
using System;
using System.Diagnostics;
using System.Runtime.InteropServices;
namespace CLRAttributes
{
  publich class MainApplication
  {
     MISSING CODE
  }
}
 
Result

Conditional methods must be marked with the Conditional attribute and the circumstances under which they will execute. So in this case, you enter the code [Conditional(“DEBUGGING”)].
Step 4 of 4

The Conditional attribute is only one of the intrinsic attributes defined in C#.
The MessageBox method uses a function that is not defined in the .NET library. Which attribute should mark it?
 
#define DEBUGGING
using System;
using System.Diagnostics;
using System.Runtime.InteropServices;
namespace CLRAttributes
{
    public class MainApplication
    {        
       [Conditional("DEBUGGING")]
       public static void DisplayMessage()
       {
           Console.WriteLine("Starting Main method");
       }

       public static extern int MessageBox(int hWnd, string strMessage, string strCaption, int uiType);   

       public static void Main ()
       {
			DisplayMessage();
			MessageBox(0,"Hello from Win API","User32.dll MessageBox",0);
			Console.ReadLine();
       }
   }
}

prajapat