.NET API Documentation

Overview

The System.Reflection.CustomAttributeProvider abstract class defines methods that allow derived classes to retrieve custom attributes applied to members of a program.

It is the base for types such as Assembly, MemberInfo, and ParameterInfo, enabling a consistent way to query attribute data.

Methods

  • GetCustomAttributes() – Returns an array of all custom attributes applied to the member.
  • GetCustomAttributes(Type attributeType, bool inherit) – Returns an array of custom attributes of a specified type.
  • IsDefined(Type attributeType, bool inherit) – Determines whether one or more instances of a specified attribute type are applied to the member.

Example

The following code demonstrates how to retrieve custom attributes from a class.

using System;
using System.Reflection;

[Obsolete("Use NewClass instead")]
public class OldClass
{
    [Obsolete]
    public void OldMethod() { }
}

class Program
{
    static void Main()
    {
        Type t = typeof(OldClass);
        var attrs = t.GetCustomAttributes(false);
        foreach (var a in attrs)
        {
            Console.WriteLine(a);
        }

        MethodInfo mi = t.GetMethod("OldMethod");
        bool hasObsolete = mi.IsDefined(typeof(ObsoleteAttribute), false);
        Console.WriteLine($"OldMethod has Obsolete: {hasObsolete}");
    }
}

Remarks

When inherit is set to true, the methods also search the inheritance chain for attributes defined on base classes.

Custom attributes are a powerful way to add declarative information to programs that can be inspected at runtime.