0
0
CsharpHow-ToBeginner · 3 min read

How to Create Custom Attribute in C# - Simple Guide

In C#, create a custom attribute by defining a class that inherits from System.Attribute. Use [AttributeUsage] to specify where the attribute can be applied, then apply it with square brackets [] on classes, methods, or properties.
📐

Syntax

To create a custom attribute, define a class that inherits from System.Attribute. Optionally, use [AttributeUsage] to control where the attribute can be applied (e.g., class, method, property). The attribute class name usually ends with Attribute.

  • AttributeUsage: Specifies valid targets and usage rules.
  • Constructor: Defines parameters for the attribute.
  • Properties: Optional data stored in the attribute.
csharp
using System;

[AttributeUsage(AttributeTargets.Class | AttributeTargets.Method)]
public class MyCustomAttribute : Attribute
{
    public string Description { get; }

    public MyCustomAttribute(string description)
    {
        Description = description;
    }
}
💻

Example

This example shows how to create a custom attribute and apply it to a class and a method. It also demonstrates how to read the attribute values using reflection.

csharp
using System;
using System.Reflection;

[AttributeUsage(AttributeTargets.Class | AttributeTargets.Method)]
public class MyCustomAttribute : Attribute
{
    public string Description { get; }

    public MyCustomAttribute(string description)
    {
        Description = description;
    }
}

[MyCustomAttribute("This is a sample class")]
public class SampleClass
{
    [MyCustomAttribute("This is a sample method")]
    public void SampleMethod() { }
}

class Program
{
    static void Main()
    {
        Type type = typeof(SampleClass);

        // Get attribute on class
        var classAttr = (MyCustomAttribute)Attribute.GetCustomAttribute(type, typeof(MyCustomAttribute));
        Console.WriteLine($"Class attribute description: {classAttr.Description}");

        // Get attribute on method
        MethodInfo method = type.GetMethod("SampleMethod");
        var methodAttr = (MyCustomAttribute)Attribute.GetCustomAttribute(method, typeof(MyCustomAttribute));
        Console.WriteLine($"Method attribute description: {methodAttr.Description}");
    }
}
Output
Class attribute description: This is a sample class Method attribute description: This is a sample method
⚠️

Common Pitfalls

  • Forgetting to inherit from System.Attribute will make your class not recognized as an attribute.
  • Not using [AttributeUsage] can lead to attributes being applied in unintended places.
  • Attribute class names should end with Attribute, but when applying, you can omit this suffix.
  • Trying to use complex types or non-constant values as attribute parameters is not allowed; use simple types like string, int, bool.
csharp
using System;

// Wrong: Does not inherit from Attribute
public class WrongAttribute
{
}

// Right: Inherits from Attribute
public class RightAttribute : Attribute
{
}

// Wrong usage: Applying attribute with wrong name
// [Wrong] // This will cause a compile error

// Right usage: Applying attribute
// [Right] // This works because suffix 'Attribute' is optional
📊

Quick Reference

Remember these key points when creating custom attributes:

  • Inherit from System.Attribute.
  • Use [AttributeUsage] to limit where the attribute applies.
  • Attribute class names end with Attribute, but usage can omit this suffix.
  • Constructor parameters must be simple constant types.
  • Use reflection to read attribute data at runtime.

Key Takeaways

Create a custom attribute by inheriting from System.Attribute.
Use [AttributeUsage] to specify valid targets for your attribute.
Attribute class names should end with 'Attribute', but you can omit this suffix when applying.
Attribute constructor parameters must be simple constant types like string or int.
Use reflection to access custom attribute data at runtime.