Introduction
Today we will look at creating custom attributes in .NET. Attributes provide metadata for the elements in our code. These can then be read via reflection and used to handle different conditional logic. The process to create and use them is simple. We will work through an example.
The Process
We will create a custom attribute and apply it to two different classes. Please note that this can be applied to other artifacts as well. I am using Visual Studio 2022 community edition for this article.
We now add a new class for the attribute.
Once created, add the below code to it.
namespace CustomAttribute {
[AttributeUsage(AttributeTargets.Class)]
public class MyDotNetAttribute: Attribute {
public string ? DataReport {
get;
set;
}
}
}
Using the Custom Attribute
We will now create two classes and apply the custom attribute to them.
namespace CustomAttribute {
[MyDotNet(DataReport = "EmployeeData")]
public class Employee {
public int Id {
get;
set;
}
public string ? FirstName {
get;
set;
}
public string ? LastName {
get;
set;
}
}
}
namespace CustomAttribute {
[MyDotNet(DataReport = "EmployeeSalaryData")]
public class Salary {
public int EmployeeId {
get;
set;
}
public double EmployeeSalary {
get;
set;
}
}
}
Finally, we will update the “Program.cs” file as below:
// Create instances for the Employee and Salary classes
using CustomAttribute;
var employee = new Employee {
Id = 1, FirstName = "John", LastName = "Doe"
};
var salary = new Salary {
EmployeeId = 1, EmployeeSalary = 5000.00
};
// Now suppose we want to extract all classes with Employee related Data using reflection to generate some report etc.
var value = GetAttributeValue(employee);
Console.WriteLine(value);
value = GetAttributeValue(salary);
Console.WriteLine(value);
string GetAttributeValue < T > (T className) {
var value = "Blank";
var myAttributes = (MyDotNetAttribute[]) className.GetType().GetCustomAttributes(typeof(MyDotNetAttribute), true);
if (myAttributes.Length > 0) {
var myAttribute = myAttributes[0];
value = myAttribute.DataReport;
}
return value;
}
In the above code, we see that we are extracting the attribute value using reflection. We can than use these values to implement our application logic as required.
Running the code gives us the below result:
Summary
In this article, we looked at creating custom attributes in .NET using C#. These will help us to add metadata to our artifacts like classes etc. We can than read these custom attributes in our application code using reflection and apply different logic depending upon the value that is extracted.