Introduction
In this article, I will show you how to use custom attributes in C# to add metadata to your code elements. Metadata is information that describes your code, such as its purpose, behavior, or usage. You can use metadata to enhance your code functionality, such as performing code analysis, serialization, or custom actions.
What are Custom Attributes?
Custom attributes are classes that inherit from the Attribute class in the System namespace. They allow you to attach metadata to your code elements, such as types, methods, properties, and so on. You can define your own custom attributes by using the [AttributeUsage] attribute to specify which code elements can be decorated with your custom attribute.
For example, the following code defines a custom attribute named MyCustomAttribute, which can be applied to classes and methods. It has a property named Description, which stores a string value that describes the code element.
using System;
[AttributeUsage(AttributeTargets.Class | AttributeTargets.Method)]
public class MyCustomAttribute : Attribute
{
public string Description { get; }
public MyCustomAttribute(string description)
{
Description = description;
}
}
How to Apply Custom Attributes?
You can apply custom attributes to your code elements by using square brackets [ ] and specifying the attribute name and any parameters. For example, the following code applies the MyCustomAttribute to a class named SampleClass and a method named SampleMethod, and passes a string value as the description parameter.
[MyCustom("This is a sample class.")]
public class SampleClass
{
[MyCustom("This is a sample method.")]
public void SampleMethod()
{
// Method implementation
}
}
How to Retrieve Custom Attributes?
You can retrieve custom attributes from your code elements by using reflection. Reflection is a feature of C# that allows you to inspect and manipulate your code at runtime. You can use the GetCustomAttributes method of the Type class or the MemberInfo class to get an array of custom attributes applied to a code element. You can then cast the array elements to your custom attribute type and access their properties.
For example, the following code uses reflection to get and display the custom attributes applied to the SampleClass and the SampleMethod.
using System;
public class Program
{
public static void Main()
{
// Get attributes on class
var classAttributes = typeof(SampleClass).GetCustomAttributes(typeof(MyCustomAttribute), false);
if (classAttributes.Length > 0)
{
var attribute = (MyCustomAttribute)classAttributes[0];
Console.WriteLine($"Class Description: {attribute.Description}");
}
// Get attributes on method
var methodAttributes = typeof(SampleClass).GetMethod("SampleMethod").GetCustomAttributes(typeof(MyCustomAttribute), false);
if (methodAttributes.Length > 0)
{
var attribute = (MyCustomAttribute)methodAttributes[0];
Console.WriteLine($"Method Description: {attribute.Description}");
}
}
}
Output
Class Description: This is a sample class.
Method Description: This is a sample method.
Why Use Custom Attributes?
Custom attributes can be used for various purposes, such as.
- Defining validation rules for your data models, such as required fields, data types, or range constraints.
- Defining serialization instructions for your data objects, such as which properties to include or exclude, or how to format them.
- Defining custom documentation for your code elements, such as summary, remarks, or examples.
- Defining custom behaviors for your code elements, such as logging, caching, or authorization.
Custom attributes are commonly used in libraries and frameworks to extend the functionality of code based on metadata. For example, ASP.NET Core uses custom attributes to define routing, filters, or model binding for controllers and actions. Entity Framework Core uses custom attributes to define database mappings, relationships, or indexes for entities and properties. NUnit uses custom attributes to define test cases, categories, or assertions for test methods and classes.
Conclusion
In this article, I have shown you how to use custom attributes in C# to add metadata to your code elements. You have learned how to define, apply, and retrieve custom attributes using reflection. You have also learned some of the benefits and use cases of custom attributes in C#.
Thank you for reading!