Using Attributes With C# .NET

 

Introduction


This dissertation is about attributes. You'll see how to define attributes on various items within your program. I will also discuss the most innovative features that the .NET framework has to offer: custom attributes, a mechanism that allows you to associate custom metadata with program elements. This metadata is created at compile time and implanted in an assembly. You can then scrutinize the metadata at runtime using reflection.
 
Attributes in C# 

Attributes


Attributes are like adjectives, which are used for metadata annotation that can be applied to a given type, assembly, module, method and so on. The .NET framework stipulates two types of attribute implementations, which are Predefined Attributes and Custom Attributes.

Attributes are types derived from the System.Attribute class. This is an abstract class defining the required services of any attribute. The following is the syntax of an attribute;

[type: attributeName(parameter1, parameter2,.........n)]

The attribute name is the class name of the attribute. Attributes can have zero or more parameters. The following code sample states the attributes implementation in which we are declaring a method as deprecated using the obsolete attribute:

 

  1. using System;   
  2. namespace attributes  
  3. {  
  4.     class Program  
  5.     {  
  6.         static void Main(string[] args)  
  7.         {  
  8.             Console.WriteLine("Attributes sample");  
  9.             TestMethod();  
  10.             Console.ReadKey();    
  11.         }  
  12.         [Obsolete("Deprecated Method",false)]  
  13.         public static void TestMethod()  
  14.         {  
  15.             Console.WriteLine("Hello world");    
  16.         }  
  17.     }  
  18. }  
The following figure shows the MSIL code of the TestMethod method as displayed in ILDASM. Notice the custom directive that defines the Obsolete attribute.

image2.gif

Role of Attributes


Attributes might be useful for documentation purposes. They fulfill many roles, including describing serialization, indicating conditional compilation, specifying import linkage and setting class blueprint and so on. Attributes allow information to be defined and applied to nearly any metadata table entry. This extensible metadata information can be queried at run time to dynamically alter the way code executes.

The C# compiler itself has been programmed to discover the presence of numerous attributes during the compilation process. For example, if the csc.exe compiler discovers an item being annotated with the [obsolete] attribute, it will display a compiler warning in the IDE error list.

Predefined Attributes


The predefined attributes have been defined by Microsoft as a part of .NET FCL, and many of them receive special support from the C# compiler. Which implies that for those specific attributes, the compiler could customize the compilation process in a specific way.

The System.Attribute base class library provides a number of attributes in various namespaces. The following table gives a snapshot of some predefined attributes.

image1.gif

To illustrate the predefined attributes in action, let's create a console based application to apply the implementation of them.

[Serialization] and [NonSerialization]

Here, assume that you have developed a Test class that can be persisted in a binary format using the [Serialization] attribute.
  1. [Serializable]  
  2. public class test  
  3. {  
  4.       public Test() { }   
  5.       string name;  
  6.       string coutnry;  
  7.       [NonSerialized]  
  8.       int salary;  
  9. }  
Once the class has been compiled, you can view the extra metadata using the ildasm.exe utility. Notice the red triangle, where these attributes are recorded using the serializable token and the salary field is tokenized using the nonserilaized attribute as in the following.

image3.gif

[WebMethod]

The following example depicts the implementation of XML web services. Here, the UtilityWebService class is annotated with [WebService] attributes. This class defines two methods marked with [WebMethod] attributes.
  1. [WebService(Namespace = "http://tempuri.org/")]  
  2. [WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]  
  3. // To allow this Web Service to be called from script, using ASP.NET AJAX, uncomment the following line.   
  4. // [System.Web.Script.Services.ScriptService]  
  5. public class UtilityWebService : System.Web.Services.WebService {   
  6.     public UtilityWebService () {   
  7.         //Uncomment the following line if using designed components   
  8.         //InitializeComponent();   
  9.     }   
  10.     [WebMethod]  
  11.     public string HelloWorld() {  
  12.         return "Hello World";  
  13.     }   
  14.     [WebMethod]  
  15.     public int addition(int a,int b)  
  16.     {  
  17.         return a+b;  
  18.     }      
  19. }  
To refer to the usage of [WebMethod] you may refer to my artile on C# Corner http://www.c-sharpcorner.com/UploadFile/84c85b/net-web-services/

[DLLImport]


The following code plays around with the unmanaged assembly user32.dll to utilize its existing method using the [DLLImport] attributes.
  1. using System;  
  2. using System.Runtime.InteropServices;  
  3. namespace attributes  
  4. {  
  5.     public class Test  
  6.     {  
  7.         [DllImport("user32.dll", EntryPoint = "MessageBox")]  
  8.         public static extern int ShowMessageBox(int hWnd,string text, string caption,uint type);  
  9.     }  
  10.     class Program  
  11.     {  
  12.         static void Main(string[] args)  
  13.         {  
  14.             string caption = "Hello World";  
  15.             string text = "Sample Article on DLLImport Attribute";  
  16.             test.ShowMessageBox(0, text, caption, 0);     
  17.             Console.ReadKey();    
  18.         }          
  19.     }  
  20. }  
Note: a member can assign more than one attribute and can be applied multiple times itself.

Once this code is compiled successfully, it produces the following output as in the following:

image4.gif

[CLSCompliant]

If you annotate this attribute at the assembly or module level and you try to use the following non CLR compliant code, then the compiler issues a warning message.

image5.gif

To refer to the usage of [CLSCompliant] you may refer to my artile on C# Corner http://www.c-sharpcorner.com/UploadFile/84c85b/cross-language-interoperability-with-C-Sharp-net/

Custom Attributes


We can create custom attributes for private usage or to be published in a library for others. The following steps are the definitive procedure for creating custom attributes:

 

  1. The custom attribute class should be derived from System.Attribute
  2. The Attribute name should  suffixed by "Attribute".
  3. Set the probable targets with the AttributeUsage attribute.
  4. Implement the class constructor and write-accessible properties.

The first step in building a custom attribute is to create a new class FunWith with Attribute suffix that derives from the System.Attribute class. Then define the class constructor and write an accessible property as Company subsequently.

  1. [AttributeUsage(AttributeTargets.Class)]  
  2. public class FunwithAttribute : Attribute  
  3. {  
  4.       public FunwithAttribute(string s)  
  5.       {  
  6.           this.Company = s;   
  7.       }  
  8.       public string Company { getset; }   
  9. }  
It is now time to apply a custom attribute class on another class. So we are creating another class test which has a FunWith attribute annotation in which we are passing the company name information.
  1. [Funwith("HCL Technology")]  
  2. public class test  
  3. {  
  4.       public test(string name, string country)  
  5.       {  
  6.            this.EmpName = name;  
  7.            this.Country = country;     
  8.       }  
  9.       public string FullDetails()  
  10.       {  
  11.            string str = EmpName + "-" + Country;  
  12.            return str;  
  13.       }   
  14.       private string EmpName;  
  15.       private string Country;  
  16. }  
  17. class Program  
  18. {  
  19.       static void Main(string[] args)  
  20.       {  
  21.            test obj = new test("Vidya Vrat","India");  
  22.            Console.WriteLine("Result:{0}",obj.FullDetails());  
  23.            Console.ReadKey();    
  24.        }  
  25. }  
After compiling this program, it yields the following output.

Output

Result: Vidya Vrat - India

Well, as you can notice, the custom attribute does not impose any impact on the final output. But we can reveal the annotation that occurs by attributes at the metadata level using ildasm.exe as in the following;

image6.gif

Custom defined attributes are sometimes valuable simply as information. However, the real power lies in associating with an attribute. You can read custom attributes with reflection using Attribute.GetCustomAttribute and Type.

The following code accesses the custom attribute values at runtime using reflection. Here, we are storing the custom attribute members in an array of object types, then looping through it to get the property value.
  1. static void Main(string[] args)  
  2. {  
  3.        MemberInfo info = typeof(test);  
  4.        object[] attrib = info.GetCustomAttributes(typeof(FunwithAttribute), false);  
  5.        foreach (Object attribute in attrib)  
  6.        {  
  7.              FunwithAttribute a = (FunwithAttribute)attribute;  
  8.              Console.WriteLine("Company: {0}", a.Company);                  
  9.         }  
  10. }  
The following code illustrates the actual utilization of custom attribute values. Here, I am displaying some values based on the custom attribute's Boolean value. The output varies on status True or False values.
  1. using System;  
  2. using System.Reflection;     
  3. public class CheckStatus : Attribute  
  4. {  
  5.       private bool Val = false;  
  6.       public bool status  
  7.       {  
  8.           get { return Val; }  
  9.       }  
  10.      public CheckStatus(bool val)  
  11.      {  
  12.           Val = val;  
  13.      }  
  14. }  
Now we are annotating the Custom Attribute in the Test class. Here, we need to configure the CheckStatus value to true to false manually. In the FullDetails() method, we are accessing the custom attributes members by foreach loop construct and later we are checking whether the status value is true or false.

 

  1. [CheckStatus(false)]  
  2. public class test  
  3. {   
  4.    private string EmpName;  
  5.    private string Country;   
  6.    public test(string name, string country)  
  7.    {  
  8.         this.EmpName = name;  
  9.         this.Country = country;     
  10.    }  
  11.    public string FullDetails()  
  12.    {  
  13.         string str = null;  
  14.         Type type = this.GetType();   
  15.         CheckStatus[] attrib =   
  16.            (CheckStatus[])type.GetCustomAttributes(typeof(CheckStatus), false);   
  17.         if (attrib[0].status == true)  
  18.         {  
  19.              str = EmpName + "-" + Country;  
  20.          }  
  21.         else  
  22.          {  
  23.              str = "Hi " + EmpName;  
  24.          }   
  25.          return str;  
  26.     }  
  27. }  
  28. class Program  
  29. {  
  30.     static void Main(string[] args)  
  31.     {  
  32.          test obj = new test("Vidya Vrat","India");  
  33.          Console.WriteLine("Result:{0}",obj.FullDetails());  
  34.          Console.ReadKey();    
  35.     }  
  36. }  
After successfully compiling this code, the following figure depicts the output from both cases:

Result : Vidya Vrat - India
Status = True
Result: Hi Vidya Vrat
Starus = False


Rather than applying attributes on an individual type, it is also possible to apply an attribute on all the types within a given assembly. To do so, simply add the attributes at assembly level in the AssemblyInfo.cs file. This file is a handy place to put attributes to be applied at the assembly level.
  1. using System.Reflection;  
  2. using System.Runtime.CompilerServices;  
  3. using System.Runtime.InteropServices;   
  4.   
  5. [assembly: AssemblyTitle("CustomAttribute")]  
  6. [assembly: AssemblyDescription("")]  
  7. [assembly: AssemblyConfiguration("")]  
  8. [assembly: AssemblyCompany("")]  
  9. [assembly: AssemblyProduct("CustomAttribute")]  
  10. [assembly: AssemblyCopyright("Copyright ©  2013")]  
  11. [assembly: AssemblyTrademark("")]  
  12. [assembly: AssemblyCulture("")]  
  13. [assembly: ComVisible(false)]  
  14. [assembly: Guid("ce5fc30b-e670-4115-aa64-4be10e7b6ea9")]  
  15. [assembly: AssemblyVersion("1.0.0.0")]  
  16. [assembly: AssemblyFileVersion("1.0.0.0")]