0
0
CsharpHow-ToBeginner · 3 min read

How to Read Attribute Using Reflection in C#

To read an attribute using reflection in C#, get the Type of the target class or member, then use GetCustomAttributes or GetCustomAttribute methods to retrieve the attribute instance. You can then access the attribute's properties directly from that instance.
📐

Syntax

Use reflection to get attributes by first obtaining the Type or MemberInfo of the target, then call GetCustomAttributes or GetCustomAttribute specifying the attribute type.

  • Type type = typeof(MyClass); — gets the class type.
  • var attrs = type.GetCustomAttributes(typeof(MyAttribute), inherit: false); — gets all attributes of type MyAttribute.
  • var attr = type.GetCustomAttribute<MyAttribute>(); — gets a single attribute instance.
csharp
using System;
using System.Reflection;

// Get the Type object
Type type = typeof(MyClass);

// Get all attributes of a specific type
object[] attrs = type.GetCustomAttributes(typeof(MyAttribute), false);

// Or get a single attribute instance
MyAttribute attr = type.GetCustomAttribute<MyAttribute>();
💻

Example

This example shows how to define a custom attribute, apply it to a class, and then read it using reflection to print its property.

csharp
using System;
using System.Reflection;

[AttributeUsage(AttributeTargets.Class)]
public class InfoAttribute : Attribute
{
    public string Description { get; }
    public InfoAttribute(string description)
    {
        Description = description;
    }
}

[Info("This is a sample class.")]
public class SampleClass
{
}

class Program
{
    static void Main()
    {
        Type type = typeof(SampleClass);
        InfoAttribute attr = type.GetCustomAttribute<InfoAttribute>();
        if (attr != null)
        {
            Console.WriteLine($"Description: {attr.Description}");
        }
        else
        {
            Console.WriteLine("Attribute not found.");
        }
    }
}
Output
Description: This is a sample class.
⚠️

Common Pitfalls

  • Forgetting to specify inherit: false or true correctly when calling GetCustomAttributes can cause missing attributes.
  • Trying to cast the attribute incorrectly or not checking for null before accessing properties leads to exceptions.
  • Using reflection on the wrong MemberInfo (e.g., method instead of class) will not find the attribute.
csharp
using System;
using System.Reflection;

[AttributeUsage(AttributeTargets.Class)]
public class MyAttr : Attribute
{
    public string Name { get; }
    public MyAttr(string name) => Name = name;
}

[MyAttr("Test")]
public class MyClass {}

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

        // Wrong: forgetting to check for null
        MyAttr attr = type.GetCustomAttribute<MyAttr>();
        Console.WriteLine(attr.Name); // Works here but risky if attr is null

        // Safe way
        if (attr != null)
        {
            Console.WriteLine(attr.Name);
        }
        else
        {
            Console.WriteLine("Attribute not found.");
        }
    }
}
Output
Test
📊

Quick Reference

Remember these key points when reading attributes with reflection:

  • Use typeof(ClassName) to get the type.
  • Use GetCustomAttribute<AttributeType>() for a single attribute.
  • Use GetCustomAttributes(typeof(AttributeType), inherit) for multiple.
  • Always check for null before using the attribute.

Key Takeaways

Use reflection's GetCustomAttribute or GetCustomAttributes to read attributes in C#.
Always check if the attribute instance is null before accessing its properties.
Specify the correct target type and attribute type when retrieving attributes.
Remember to handle inheritance with the inherit parameter when needed.