| by Arround The Web | No comments

How to Use Custom Attributes in C#

Attributes in C# provide a way to add metadata or declarative information to code elements such as classes, methods, properties, and parameters. This metadata can be used by the compiler or other tools to generate code or provide additional functionality. In this article, we will discuss how to work with attributes in C# and provide examples of defining and using custom attributes.

How to Work with Custom Attributes in C#

Attributes play an essential role in C# programming and are a powerful way to add declarative information to code. They can be used to decorate classes, methods, properties, fields, events, and even parameters. To work with attributes or to use them effectively in C# here are a few things that you need to know:

1: Defining Custom Attributes

Custom attributes can be defined in C# by creating a class that inherits from the System.Attribute base class. The term “Attribute” should be at the end of the name of the attribute class. The attribute class can have fields, properties, or methods to store the metadata. The public access modifier should be used to indicate the fields and properties, and the public or private access modifier should be used to designate the methods. Here is an example of defining a custom attribute with three properties: Name, Designation, and Qualification:

using System;

[AttributeUsage(AttributeTargets.Class)]
public class EmployeeAttribute : Attribute
{
    public string Name { get; set; }
    public string Designation { get; set; }
    public string Qualification { get; set; }
}

In the above code, we define an attribute named EmployeeAttribute that can be applied to a class. The type of code element to which the custom attribute can be applied is specified using the AttributeUsage attribute. In this case, we set it to AttributeTargets.Class to indicate that the custom property is only applicable to classes.

2: Using Custom Attributes

Once a custom attribute is defined, we can apply it to a class or other code element by enclosing it in square brackets and placing it above the code element. Here is an example of using the EmployeeAttribute custom attribute:

[Employee(Name = "Sam", Designation = "Graphic Designer", Qualification = "Bachelor's degree")]
public class Employee
{
    // class implementation
}

In this code, we apply the EmployeeAttribute custom attribute to the Employee class by enclosing it in square brackets above the class definition. The attribute has three properties – Name, Designation, and Qualification – which are set to specific values for the Employee class. This allows us to attach metadata to the Employee class that can be accessed at runtime using reflection.

3: Accessing Custom Attributes Using Reflection

To access the custom attribute applied to a code element at runtime, we can use reflection. Here is an example of how to access the EmployeeAttribute custom attribute applied to the Employee class:

EmployeeAttribute attribute = (EmployeeAttribute)typeof(Employee).GetCustomAttributes(typeof(EmployeeAttribute), true)[0];

Console.WriteLine($"Employee name: {attribute.Name}");
Console.WriteLine($"Employee designation: {attribute.Designation}");
Console.WriteLine($"Employee qualification: {attribute.Qualification}");

In the above code, we use the typeof() method to get the Type object for the Employee class, and then call the GetCustomAttributes() method to get an array of custom attributes applied to the class. We then cast the first element of the array to the EmployeeAttribute type and access its properties.

Here is a complete code that illustrates the use of attributes in c# as it defines three custom attributes, NameAttribute, DesignationAttribute, and QualificationAttribute, each of which takes a single string parameter:

using System;

[AttributeUsage(AttributeTargets.Class)]
public class NameAttribute : Attribute
{
    public string Name { get; private set; }

    public NameAttribute(string name)
    {
        Name = name;
    }
}

[AttributeUsage(AttributeTargets.Class)]
public class DesignationAttribute : Attribute
{
    public string Designation { get; private set; }

    public DesignationAttribute(string designation)
    {
        Designation = designation;
    }
}

[AttributeUsage(AttributeTargets.Class)]
public class QualificationAttribute : Attribute
{
    public string Qualification { get; private set; }

    public QualificationAttribute(string qualification)
    {
        Qualification = qualification;
    }
}

[Name("Sam")]
[Designation("Team Manager")]
[Qualification("Bachelor of Science in Electrical Engineering")]
class Employee
{
    public string Name { get; set; }

}

class Program
{
    static void Main(string[] args)
    {
        Type employeeType = typeof(Employee);

        Console.WriteLine("Employee Information:");
        Console.WriteLine($"Name: {((NameAttribute)Attribute.GetCustomAttribute(employeeType, typeof(NameAttribute))).Name}");
        Console.WriteLine($"Designation: {((DesignationAttribute)Attribute.GetCustomAttribute(employeeType, typeof(DesignationAttribute))).Designation}");
        Console.WriteLine($"Qualification: {((QualificationAttribute)Attribute.GetCustomAttribute(employeeType, typeof(QualificationAttribute))).Qualification}");
    }
}

This C# code defines a class called Employee and three custom attributes: NameAttribute, DesignationAttribute, and QualificationAttribute. The Employee class has a single property for the name of the employee. Using the custom attributes, you can add extra details about the employee, like their name, title, and education.

In the Main method, the typeof operator is used to get the Type of the Employee class and the Attribute.GetCustomAttribute method is used to retrieve the values of the custom attributes for that class. The retrieved attribute values are then displayed on the console using Console.WriteLine statements.

Conclusion

The attributes provide a powerful mechanism for adding metadata or declarative information to code elements in C#. By defining custom attributes and applying them to code elements, we can create more expressive and self-documenting code. We can also use reflection to access the custom attributes at runtime and provide additional functionality.

Share Button

Source: linuxhint.com

Leave a Reply