C# `Type.GetCustomAttributes()`: Retrieving Custom Attributes using Reflection

Master C# reflection with the `Type.GetCustomAttributes()` method. This tutorial demonstrates how to retrieve custom attributes applied to types, explaining the use of the `inherit` parameter and providing practical examples for using attribute metadata at runtime.



Using C#'s `Type.GetCustomAttributes()` Method for Reflection

The C# `Type.GetCustomAttributes()` method is a powerful reflection tool that allows you to retrieve custom attributes applied to a type (class, interface, struct, enum, etc.). Reflection lets you examine and manipulate type information at runtime.

Understanding Custom Attributes

Custom attributes in C# provide a way to add metadata to your code. They're essentially annotations that you define and apply to types or members to convey extra information that's not directly part of the language. This information can be used at compile time or at runtime.

`Type.GetCustomAttributes()` Method

The `Type.GetCustomAttributes()` method retrieves an array of `object` instances representing the custom attributes applied to a specific type. This method is especially valuable when working with reflection and handling situations in which the type's characteristics must be examined during the runtime.


public virtual object[] GetCustomAttributes(bool inherit);

The parameter `inherit` determines whether to include inherited attributes. Set it to `true` to include attributes from base classes; `false` to only get attributes directly applied to the current type.

Example 1: Retrieving a Custom Attribute


[AttributeUsage(AttributeTargets.Class)]
public class MyAttribute : Attribute {
    public string Message { get; set; }
}

[MyAttribute(Message = "Hello from attribute!")]
public class MyClass { }

public class GetAttributesExample {
    public static void Main(string[] args) {
        // Get the type of MyClass
        Type type = typeof(MyClass);
        // Get the custom attributes
        object[] attributes = type.GetCustomAttributes(false);
        // Iterate through and print the custom attributes
    }
}

Example 2: Retrieving Inherited Attributes


[AttributeUsage(AttributeTargets.Class)]
public class MyAttribute : Attribute { public string Description { get; set; } }

[MyAttribute(Description = "Base Class")]
public class BaseClass { }

[MyAttribute(Description = "Derived Class")]
public class DerivedClass : BaseClass { }

// ... (code to retrieve attributes, including inherited ones, using GetCustomAttributes(true)) ...

Uses of `Type.GetCustomAttributes()`

  • Reflection: Dynamically inspect types at runtime.
  • Data Annotation: Add metadata for database mappings, validation, serialization.
  • Runtime Behavior: Control program behavior based on attributes (e.g., security).
  • Code Generation: Use attributes as markers for code generation tools.

Retrieving Custom Attributes in C# Using `Type.GetCustomAttributes()`

This article demonstrates how to use the C# `Type.GetCustomAttributes()` method to retrieve custom attributes associated with a type at runtime. Custom attributes provide a way to add metadata to your code, enhancing its functionality and flexibility.

Understanding Custom Attributes and Reflection

Custom attributes in C# are a powerful way to add extra information to your classes, methods, properties, etc. They're not directly part of the code's execution but provide metadata that can be used for various purposes (like code generation, validation, or serialization). Reflection allows you to examine this metadata at runtime.

`Type.GetCustomAttributes()` Method

The `Type.GetCustomAttributes()` method retrieves custom attributes applied to a type. It's a very important tool for working with reflection.


public virtual object[] GetCustomAttributes(bool inherit);

This method takes a boolean value (`inherit`) indicating whether to include inherited attributes. If `inherit` is `true`, it retrieves attributes from base classes. If `false`, only attributes directly on the type are returned.

Example: Retrieving a Custom Attribute

This example shows how to retrieve a custom attribute from a class at runtime using reflection.


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

[MyCustomAttribute(Description = "My Class")]
public class MyClass { }

public class GetAttributesExample {
    public static void Main(string[] args) {
        // ... (code to get MyClass's type, get custom attributes using GetCustomAttributes(false), and print the Description property) ...
    }
}

Explanation

The example defines a custom attribute (`MyCustomAttribute`) and applies it to a class (`MyClass`). The `Main` method uses reflection (`typeof(MyClass)`) to get the type information. `GetCustomAttributes(false)` retrieves only the attributes directly on the class, not inherited ones. The code then iterates through the attributes, checking if each attribute is of type `MyCustomAttribute` and printing the `Description` if it is.

Uses of `Type.GetCustomAttributes()`

  • Reflection-based tools: Dynamically analyze types at runtime.
  • Metadata-driven programming: Control application behavior based on attributes.
  • Code generation: Generate code based on attribute markers.