In C#, you can create your own custom attributes, which are pieces of metadata associated with your code elements: classes, methods, properties, etc., that can later be read through reflection. Let's see the step-by-step guide to create a custom attribute in C#.
Create a Custom Attribute Class A custom attribute is simply a class that derives from System.Attribute namespace.
using System;
[AttributeUsage(AttributeTargets.Class | AttributeTargets.Method | AttributeTargets.Property, AllowMultiple = false)]
public class AuthorAttribute : Attribute
{
public string UserName { get; }
public string Version { get; set; }
public AuthorAttribute(string name)
{
UserName = name;
Version = "1.0";
}
}
Note:AttributeTargets.Class is allowed to use this attribute with the classes,
AttributeTargets.Method is allowed to use with methods and AttributeTargets.Property allows to use of properties. You can also allow this attribute to be used only with the call by setting the
AttributeTargets.Class.
You can also allow multiple uses with AllowMultiple = true.
Apply the Attribute
Now you can use this attribute to decorate your class, method, or property:
[Author("Manish Sharma", Version = "2.3")]
public class ClassName
{
[Author("Pooja Verma")]
public void MethodName()
{
Console.WriteLine("Hello C# developer");
}
}
Retrieve the Attribute via Reflection
You can read attribute data at runtime like given below:
using System;
using System.Reflection;
class Program
{
static void Main()
{
Type type = typeof(ClassName);
// Get class attribute
var classAttr = (AuthorAttribute)Attribute.GetCustomAttribute(type, typeof(AuthorAttribute));
Console.WriteLine($"Class Author: {classAttr.UserName}, Version: {classAttr.Version}");
// Get method attribute
MethodInfo method = type.GetMethod("MethodName");
var methodAttr = (AuthorAttribute)Attribute.GetCustomAttribute(method, typeof(AuthorAttribute));
Console.WriteLine($"Method Author: {methodAttr.UserName}, Version: {methodAttr.Version}");
}
}
Output
Class Author: Manish Sharma, Version: 2.3
Method Author: John Doe, Version: 1.0
We use cookies to ensure you have the best browsing experience on our website. By using our site, you
acknowledge that you have read and understood our
Cookie Policy &
Privacy Policy.
In C#, you can create your own custom attributes, which are pieces of metadata associated with your code elements: classes, methods, properties, etc., that can later be read through reflection.
Let's see the step-by-step guide to create a custom attribute in C#.
Create a Custom Attribute Class
A custom attribute is simply a class that derives from
System.Attributenamespace.You can also allow multiple uses with
AllowMultiple = true.Apply the Attribute
Now you can use this attribute to decorate your class, method, or property:
Retrieve the Attribute via Reflection
You can read attribute data at runtime like given below:
Output
Would you learn about: What is the difference between throw and throw ex?