CKTIS / C#
GetCustomAttribute<T> — reading a single attribute
CustomAttributeExtensions.GetCustomAttribute<T> retrieves a single attribute of type T through reflection. Learn its supported targets, null handling, and why multiple matches cause an exception.
Version: .NET 10; repository net10.0 and LangVersion=preview; feature versions require per-entry verification
Syntax
public static T? GetCustomAttribute<T>(this System.Reflection.MemberInfo element, bool inherit) where T : Attribute;CustomAttributeExtensions.GetCustomAttribute<T> in System.Reflection provides extension methods for MemberInfo, ParameterInfo, Assembly, and Module. T can be System.Attribute itself or a type derived from it. Importing using System.Reflection; enables element.GetCustomAttribute<T>(); for a type, use typeof(Report).
The result is a matching attribute of type T, or null when none is found. Multiple matches cause AmbiguousMatchException rather than selecting the first result. A call to GetCustomAttribute<Attribute> is valid and also throws this exception if more than one attribute matches. Use GetCustomAttributes<T> when you expect multiple attributes. A null argument for element causes ArgumentNullException.
Overloads for MemberInfo and ParameterInfo also accept bool inherit. false limits the lookup to attributes applied directly to the target, while true considers inheritance only where the target supports it. A parameter of an overriding method can inherit attributes from the corresponding parameter of the base method, but a constructor parameter has no such inheritance chain. Attributes marked Inherited = false are not inherited. The example explicitly limits the search with inherit: false; the result Monthly comes from the LabelAttribute applied to Report.
Examples
using System;
using System.Reflection;
LabelAttribute? label = typeof(Report)
.GetCustomAttribute<LabelAttribute>(inherit: false);
Console.WriteLine(label?.Text ?? "missing");
[AttributeUsage(AttributeTargets.Class)]
public sealed class LabelAttribute : Attribute
{
public LabelAttribute(string text) => Text = text;
public string Text { get; }
}
[Label("Monthly")]
public sealed class Report { }
Result
Monthly
The displayed code and declared result were verified in an isolated environment using the method recorded in the verification evidence for this exact version.