Open In App

Custom Attributes in C#

Last Updated : 24 Jun, 2019
Improve
Improve
Like Article
Like
Save
Share
Report

Attributes are metadata extensions that give additional information to the compiler about the elements in the program code at runtime. Attributes are used to impose conditions or to increase the efficiency of a piece of code. There are built-in attributes present in C# but programmers may create their own attributes, such attributes are called Custom attributes. To create custom attributes we must construct classes that derive from the System.Attribute class.

Steps to create a Custom Attribute

1. Using the AttributeUsageAttribute: This tag defines the attribute that we are constructing. It provides information such as what the attribute targets are, if it can be inherited or if multiple instances of this attribute can exist. The AttributeUsageAttribute has three primary members as follows:

  1. AttributeTargets.All specifies that the attribute may be applied to all parts of the program whereas Attribute.Class indicates that it may be applied to a class and AttributeTargets.Method to a method.
    [AttributeUsageAttribute( AttributeTargets.All )]
    
  2. Inherited member is indicative of if the attribute might be inherited or not. It takes a boolean value (true/false). If this is not specified then the default is assumed to be true.
    [AttributeUsage(AttributeTargets.All, Inherited = false)]
    
  3. AllowMultiple member tells us if there can exist more than one instances of the attribute. It takes a boolean value as well. It is false by default.
    [AttributeUsage(AttributeTargets.Method, AllowMultiple = true)]
    
    1. 2. Defining the Attribute class: It is defined in the same way as a normal class is, the name of the class conventionally ends in ‘Attribute’. This class must inherit directly or indirectly from System.Attribute class.

      [AttributeUsage(AttributeTargets.All, Inherited = true, AllowMultiple = false)]
      public class MyAttribute : Attribute
      {
          //Class Members
      }
      

      3. Defining Constructors and Properties: The constructors are used to set the values of the Attribute class pretty much like typical classes. Constructor overloading can be used to handle different assignments while provoking Attribute class objects.

      public MyAttribute(dataType value)
      {
          this.value = value;
      }
      

      Note: Custom Attributes can have properties like get and set for its members as well.

      public dataType MyProperty
      {
          get {return this.value;}
          set {this.value = newValue;}
      }
      

      Example 1: The code given below shows an example of a Custom Attribute named MyAttribute, which has two private members namely name and action. The ‘name’ is used for defining a name for any program element that the attribute may be applied to. The ‘action’ describes what the element is supposed to do. Here the attributes are applied to methods to class Student.




      // C# program to illustrate the 
      // use of custom attributes
      using System;
        
      // Creating Custom attribute MyAttribute
        
      [AttributeUsage(AttributeTargets.All)] public class MyAttribute : Attribute {
        
          // Provides name of the member
          private string name;
        
          // Provides description of the member
          private string action;
        
          // Constructor
          public MyAttribute(string name, string action)
          {
              this.name = name;
              this.action = action;
          }
        
          // property to get name
          public string Name
          {
              get { return name; }
          }
        
          // property to get description
          public string Action
          {
              get { return action; }
          }
      }
        
      class Student {
        
          // Private fields of class Student
          private int rollNo;
          private string stuName;
          private double marks;
        
          // The attribute MyAttribute is applied 
          // to methods of class Student
          // Providing details of their utility
          [MyAttribute("Modifier", "Assigns the Student Details")] public void setDetails(int r, 
                                                                            string sn, double m)
          {
              rollNo = r;
              stuName = sn;
              marks = m;
          }
        
          [MyAttribute("Accessor", "Returns Value of rollNo")] public int getRollNo()
          {
              return rollNo;
          }
        
          [MyAttribute("Accessor", "Returns Value of stuName")] public string getStuName()
          {
              return stuName;
          }
        
          [MyAttribute("Accessor", "Returns Value of marks")] public double getMarks()
          {
              return marks;
          }
      }
        
      class TestAttributes {
        
          // Main Method
          static void Main(string[] args)
          {
              Student s = new Student();
              s.setDetails(1, "Taylor", 92.5);
        
              Console.WriteLine("Student Details");
              Console.WriteLine("Roll Number : " + s.getRollNo());
              Console.WriteLine("Name : " + s.getStuName());
              Console.WriteLine("Marks : " + s.getMarks());
          }
      }

      
      

      Output:

      Student Details
      Roll Number : 1
      Name : Taylor
      Marks : 92.5
      

      Example 2: In this example we can display the contents of the custom attribute that we created. Here the NewAttribute is a custom attribute with two fields namely title and description. The tile stores the title and description stores the function of the method to which NewAttribute is applied. The way to apply a Custom attribute to any part of the program you must call its constructor before the definition. NewAttribute also consists of a Parameterised constructor and a method to display the contents of the attribute. In the main you call the AttributeDisplay method using the class name as it is a static method, this displays the information about the methods of the classes to which the attribute is applied.




      // C# program to display the custom attributes
      using System;
      using System.Reflection;
      using System.Collections.Generic;
        
      // Defining a Custom attribute class
      class NewAttribute : Attribute {
        
          // Private fields
          private string title;
          private string description;
        
          // Parameterised Constructor
          public NewAttribute(string t, string d)
          {
              title = t;
              description = d;
          }
        
          // Method to show the Fields 
          // of the NewAttribute
          // using reflection
          public static void AttributeDisplay(Type classType)
          {
              Console.WriteLine("Methods of class {0}", classType.Name);
        
              // Array to store all methods of a class
              // to which the attribute may be applied
        
              MethodInfo[] methods = classType.GetMethods();
        
              // for loop to read through all methods
        
              for (int i = 0; i < methods.GetLength(0); i++) {
        
                  // Creating object array to receive 
                  // method attributes returned
                  // by the GetCustomAttributes method
        
                  object[] attributesArray = methods[i].GetCustomAttributes(true);
        
                  // foreach loop to read through 
                  // all attributes of the method
                  foreach(Attribute item in attributesArray)
                  {
                      if (item is NewAttribute) {
        
                          // Display the fields of the NewAttribute
                          NewAttribute attributeObject = (NewAttribute)item;
                          Console.WriteLine("{0} - {1}, {2} ", methods[i].Name,
                           attributeObject.title, attributeObject.description);
                      }
                  }
              }
          }
      }
        
      // Class Employer
      class Employer {
        
          // Fields of Employer
          int id;
          string name;
        
          // Constructor
          public Employer(int i, string n)
          {
              id = i;
              name = n;
          }
        
          // Applying the custom attribute 
          // NewAttribute to the getId method
          [NewAttribute("Accessor", "Gives value of Employer Id")] public int getId()
          {
              return id;
          }
        
          // Applying the custom attribute 
          // NewAttribute to the getName method
          [NewAttribute("Accessor", "Gives value of Employer Name")] public string getName()
          {
              return name;
          }
      }
        
      // Class Employee
      class Employee {
        
          // Fields of Employee
          int id;
          string name;
        
          public Employee(int i, string n)
          {
              id = i;
              name = n;
          }
        
          // Applying the custom 
          // attribute NewAttribute
          // to the getId method
          [NewAttribute("Accessor", "Gives value of Employee Id")] public int getId()
          {
              return id;
          }
        
          // Applying the custom attribute 
          // NewAttribute to the getName method
          [NewAttribute("Accessor", "Gives value of Employee Name")] public string getName()
          {
              return name;
          }
      }
        
      class Program {
        
          // Main Method
          static void Main(string[] args)
          {
        
              // Calling the AttributeDisplay
              // method using the class name
              // since it is a static method
              NewAttribute.AttributeDisplay(typeof(Employer));
        
              Console.WriteLine();
        
              NewAttribute.AttributeDisplay(typeof(Employee));
          }
      }

      
      

      Output:

      Methods of class Employer
      getId - Accessor, Gives value of Employer Id 
      getName - Accessor, Gives value of Employer Name 
      
      Methods of class Employee
      getId - Accessor, Gives value of Employee Id 
      getName - Accessor, Gives value of Employee Name
      


      Like Article
      Suggest improvement
      Previous
      Next
      Share your thoughts in the comments

Similar Reads