How to construct custom attributes in C#?


Attributes are used for adding metadata, such as compiler instruction and other information such as comments, description, methods, and classes to a program.

The .Net Framework allows the creation of custom attributes that can be used to store declarative information and can be retrieved at run-time.

A new custom attribute is derived from the System.Attribute class.

//a custom attribute BugFix to be assigned to a class and its members
[AttributeUsage(
AttributeTargets.Class |
AttributeTargets.Constructor |
AttributeTargets.Field |
AttributeTargets.Method |
AttributeTargets.Property,
AllowMultiple = true)]

public class DeBugInfo : System.Attribute

Let us construct a custom attribute named DeBugInfo, which stores the information obtained by debugging any program.

The DeBugInfo class has three private properties for storing the first three information and a public property for storing the message. Hence the bug number, developer's name, and date of review are the positional parameters of the DeBugInfo class and the message is an optional or named parameter.

Example

Let us see how −

//a custom attribute BugFix to be assigned to a class and its members
[AttributeUsage(
AttributeTargets.Class |
AttributeTargets.Constructor |
AttributeTargets.Field |
AttributeTargets.Method |
AttributeTargets.Property,
AllowMultiple = true)]

public class DeBugInfo : System.Attribute {
   private int bugNo;
   private string developer;
   private string lastReview;
   public string message;

   public DeBugInfo(int bg, string dev, string d) {
      this.bugNo = bg;
      this.developer = dev;
      this.lastReview = d;
   }

   public int BugNo {
      get {
         return bugNo;
      }
   }

   public string Developer {
      get {
         return developer;
      }
   }

   public string LastReview {
      get {
         return lastReview;
      }
   }
   public string Message {
      get {
         return message;
      }

      set {
         message = value;
      }
   }
}

Updated on: 20-Jun-2020

74 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements