Pages

Topics

Tools

↑↓navigate↵openescclose
All guides

C# Reflection: Get Attributes from Types and Members

Learn how to use C# reflection to retrieve custom attributes from types and members, including inheritance behavior and performance considerations.

~4 min readC#
#Reflection#Attributes#C##Metadata
Illustration of C# reflection retrieving attributes from a class member

When you need to read custom attributes from a type or member at runtime, reflection is the standard mechanism. This article covers the core System.Reflection APIs, how they behave with inheritance, and where to be careful about performance.

The Core APIs for Retrieving Attributes

The simplest way to get a single attribute instance is Attribute.GetCustomAttribute. It takes a MemberInfo (which Type, MethodInfo, PropertyInfo, and similar types inherit from) and the attribute type you're looking for. If the attribute is not present, it returns null.

Consider a custom attribute that records an author name:

csharp
[AttributeUsage(AttributeTargets.Class | AttributeTargets.Method)] public class AuthorAttribute : Attribute { public string Name { get; } public AuthorAttribute(string name) => Name = name; } [Author("Jane Doe")] public class SampleService { }

To read it:

csharp
var type = typeof(SampleService); var author = Attribute.GetCustomAttribute(type, typeof(AuthorAttribute)) as AuthorAttribute; Console.WriteLine(author?.Name); // "Jane Doe"

To retrieve all matching attributes, including inherited ones, use MemberInfo.GetCustomAttributes() or the generic GetCustomAttributes<T>() extension. Those methods return an enumerable collection you can filter or project.

csharp
var attributes = type.GetCustomAttributes<AuthorAttribute>(inherit: true); foreach (var attr in attributes) { Console.WriteLine(attr.Name); }

The inherit parameter controls whether inherited attributes are included, which we'll examine shortly.

Retrieving Attributes from Different Member Types

The same pattern works for methods, properties, fields, and parameters when the attribute's AttributeUsage permits those targets. For example, to get attributes from a method:

csharp
public class Service { [Author("John Smith")] public void Run() { } } var method = typeof(Service).GetMethod(nameof(Service.Run)); var methodAuthor = Attribute.GetCustomAttribute(method, typeof(AuthorAttribute)) as AuthorAttribute;

For properties, you first obtain the PropertyInfo via GetProperty and call GetCustomAttribute on it. Fields use FieldInfo. Parameters use ParameterInfo, which is not a MemberInfo; Attribute.GetCustomAttribute has a separate overload for it. Assembly-level attributes, such as AssemblyTitle or AssemblyVersion, are read through an overload that takes an Assembly.

When dealing with multiple members of the same kind, you can iterate over the results of GetProperties(), GetMethods(), or GetFields() and inspect each one. This is common in serialization frameworks, validation libraries, and ORMs that map attributes to behavior.

Handling Inherited Attributes

Inheritance behavior is controlled by AttributeUsageAttribute.Inherited, which defaults to true. When you query a type that derives from a base class, GetCustomAttribute will also look at base types unless you pass inherit: false.

csharp
[AttributeUsage(AttributeTargets.Class, Inherited = true)] public class MarkerAttribute : Attribute { } [Marker] public class BaseClass { } public class DerivedClass : BaseClass { } var marker = Attribute.GetCustomAttribute(typeof(DerivedClass), typeof(MarkerAttribute)); // marker is not null, even though DerivedClass does not declare it

For methods, inheritance is more subtle. An attribute on a virtual method is inherited by an overriding method only if the attribute is marked Inherited = true and the overriding method does not explicitly declare the same attribute. If the method is not virtual, the attribute is not inherited. This can lead to surprising behavior when you expect attributes to flow down an override chain. Always test the specific scenario in your codebase.

Performance Considerations and Caching

Reflection calls are significantly slower than direct code access because they involve metadata lookup, type checks, and often allocation. Calling GetCustomAttribute repeatedly in a hot path can become a measurable overhead. The standard mitigation is to cache the result after the first lookup.

A simple approach is a static ConcurrentDictionary keyed by the member and attribute type:

csharp
private static readonly ConcurrentDictionary<(MemberInfo Member, Type AttributeType), Attribute?> Cache = new(); public static T? GetCachedAttribute<T>(MemberInfo member) where T : Attribute { var key = (member, typeof(T)); return (T?)Cache.GetOrAdd(key, k => Attribute.GetCustomAttribute(k.Member, k.AttributeType)); }

This reduces repeated reflection calls to a single dictionary lookup. For applications that query attributes frequently—such as a validation engine or a serialization layer—this caching pattern is essential.

Another consideration is that GetCustomAttributes allocates a collection of Attribute objects. When the attribute type is not allowed to appear multiple times, GetCustomAttribute avoids that allocation. For multiple attributes, the collection is unavoidable, but you can avoid re-fetching by storing the result.

Common Pitfalls and Edge Cases

One frequent mistake is forgetting that GetCustomAttribute returns null when the attribute is missing. Check the result for null before using it.

Another edge case is when an attribute type can appear multiple times. GetCustomAttribute is not the right API for inspecting all instances; use GetCustomAttributes and filter by type instead. Also, be aware that the order of attributes is not guaranteed by the runtime.

Attribute usage validation is performed by the compiler at compile time when AttributeUsage restricts the targets. If you attempt to apply an attribute to an invalid target, the compiler rejects it. Reflection itself does not enforce those rules at runtime; it simply returns whatever attributes were compiled onto the member.

When to Use Reflection vs. Source Generators

Reflection is the classic way to read attributes, but it has runtime cost and no compile-time verification. In modern C#, source generators can inspect attributes at compile time and generate code that reads them without reflection. This is beneficial for scenarios like serialization, dependency injection, and logging, where the attribute set is known at compile time.

However, source generators require a separate project and more upfront complexity. Reflection remains the right choice when the attributes are discovered dynamically—for example, when loading plugins or when the set of types is not known until runtime. It also works with any .NET version without additional tooling.

A pragmatic approach is to use source generators for the hot paths and reflection for one-time initialization or dynamic scenarios. The decision depends on whether the attribute data is needed frequently and whether the cost of reflection is acceptable in your application's performance budget.

For many applications, the caching pattern described earlier makes the reflection overhead acceptable. Start with reflection and a simple cache, then profile if you are considering a source generator.

Try matching browser tools

All tools

Small utilities that fit C# work — they run entirely in this browser tab, so nothing you paste leaves your device.

All C# guides

More in C#

All C# guides

The guides filed next to this one in C#, in library order.