Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
How to create custom attributes in C#?
Custom attributes in C# allow you to store declarative information about program elements (classes, methods, properties, etc.) that can be retrieved at runtime using reflection. They provide metadata that doesn't affect program execution but can be used for documentation, validation, or configuration purposes.
Syntax
Following is the basic syntax for creating a custom attribute −
[AttributeUsage(AttributeTargets.Class | AttributeTargets.Method)]
public class CustomAttribute : System.Attribute {
// constructors and properties
}
Following is the syntax for applying the custom attribute −
[CustomAttribute(parameters)]
public class MyClass {
// class implementation
}
Creating a Custom Attribute
To create a custom attribute, you must inherit from System.Attribute and optionally use the AttributeUsage attribute to specify where your attribute can be applied.
Example
using System;
[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; }
}
}
[DebugInfo(45, "Zara Ali", "12/8/2012", message = "Return type mismatch")]
[DebugInfo(49, "Nuha Ali", "10/10/2012", message = "Unused variable")]
class Rectangle {
protected double length;
protected double width;
public Rectangle(double l, double w) {
length = l;
width = w;
}
[DebugInfo(55, "Zara Ali", "19/10/2012", message = "Return type could be double")]
public double GetArea() {
return length * width;
}
[DebugInfo(56, "Zara Ali", "19/10/2012")]
public void Display() {
Console.WriteLine("Length: {0}", length);
Console.WriteLine("Width: {0}", width);
Console.WriteLine("Area: {0}", GetArea());
}
}
class ExecuteRectangle {
public static void Main() {
Rectangle r = new Rectangle(4.5, 7.5);
r.Display();
}
}
The output of the above code is −
Length: 4.5 Width: 7.5 Area: 33.75
Reading Attribute Information Using Reflection
To retrieve custom attribute information at runtime, use reflection methods like GetCustomAttributes() −
Example
using System;
using System.Reflection;
[AttributeUsage(AttributeTargets.Class)]
public class AuthorAttribute : System.Attribute {
public string Name { get; set; }
public string Version { get; set; }
public AuthorAttribute(string name) {
Name = name;
}
}
[Author("John Doe", Version = "1.0")]
public class MyClass {
public void DoSomething() {
Console.WriteLine("Doing something...");
}
}
class Program {
public static void Main() {
Type type = typeof(MyClass);
object[] attributes = type.GetCustomAttributes(typeof(AuthorAttribute), false);
foreach (AuthorAttribute attr in attributes) {
Console.WriteLine("Author: " + attr.Name);
Console.WriteLine("Version: " + attr.Version);
}
MyClass obj = new MyClass();
obj.DoSomething();
}
}
The output of the above code is −
Author: John Doe Version: 1.0 Doing something...
AttributeUsage Parameters
| Parameter | Description |
|---|---|
AttributeTargets |
Specifies where the attribute can be applied (Class, Method, Property, etc.) |
AllowMultiple |
Indicates whether multiple instances of the attribute can be applied to the same element |
Inherited |
Specifies whether the attribute is inherited by derived classes |
Common Use Cases
-
Documentation − Store author information, version details, or bug tracking data.
-
Validation − Mark properties for data validation in frameworks like ASP.NET.
-
Serialization − Control how objects are serialized to JSON, XML, or other formats.
-
Security − Mark methods that require specific permissions or roles.
Conclusion
Custom attributes in C# provide a powerful way to add metadata to your code that can be accessed at runtime through reflection. They inherit from System.Attribute and can store both positional and named parameters, making them useful for documentation, validation, and configuration purposes.
