CKTIS / C#
Property attributes: AttributeUsage and selection with BindingFlags
Declare where an attribute is valid, select public instance properties, and distinguish attributes applied directly from those found through inheritance.
Version: C# 12 and .NET 8; later runtimes may add compatible features
Syntax
using System;
using System.Reflection;
// Model is the type to inspect.
PropertyInfo[] properties = typeof(Model).GetProperties(BindingFlags.Public | BindingFlags.Instance);
foreach (PropertyInfo property in properties)
{
LabelAttribute? label = property.GetCustomAttribute<LabelAttribute>(inherit: false);
}
[AttributeUsage(AttributeTargets.Property, AllowMultiple = false, Inherited = true)]
sealed class LabelAttribute : Attribute { }[AttributeUsage(...)] is shorthand for System.AttributeUsageAttribute on an attribute class derived from System.Attribute. AttributeTargets.Property permits the attribute on a property regardless of visibility or whether it is static. It does not target an accessor or a backing field. ValidOn reports the allowed targets. AllowMultiple (default false) controls whether the attribute can appear more than once on the same declaration; Inherited (default true) controls whether an overriding property can inherit it.
Type.GetProperties(BindingFlags.Public | BindingFlags.Instance) uses flags from System.Reflection and returns a PropertyInfo[], not property values. Reflection treats a property as public if at least one accessor is public. | is bitwise OR: the flags overload needs at least one of Public/NonPublic and one of Instance/Static. Adding DeclaredOnly excludes inherited properties from the list; it does not control the later attribute lookup.
property.GetCustomAttribute<T>(inherit: ...) is a System.Reflection.CustomAttributeExtensions extension method for MemberInfo, the base class of PropertyInfo; it is not a PropertyInfo instance method. T must derive from Attribute. The non-generic counterpart is the static Attribute.GetCustomAttribute(property, typeof(T), inherit). inherit: false checks only that property; true also searches its override chain when the attribute is inheritable. The MemberInfo.GetCustomAttributes(..., inherit) instance method ignores inherit for properties.
No match returns null; more than one match throws AmbiguousMatchException. If you expect multiple matches, use the GetCustomAttributes<T>(inherit: ...) extension. Retrieving an attribute instance can run its constructor. To inspect just the recorded arguments without instantiating the attribute, use CustomAttributeData, which does not look up inherited attributes.
Examples
#nullable enable
using System;
using System.Linq;
using System.Reflection;
var usage = typeof(LabelAttribute).GetCustomAttribute<AttributeUsageAttribute>(inherit: false)
?? throw new InvalidOperationException("Missing attribute usage metadata.");
Console.WriteLine($"Usage: {usage.ValidOn}, AllowMultiple={usage.AllowMultiple}, Inherited={usage.Inherited}");
foreach (PropertyInfo property in typeof(Item)
.GetProperties(BindingFlags.Public | BindingFlags.Instance)
.OrderBy(p => p.Name, StringComparer.Ordinal))
{
var direct = property.GetCustomAttribute<LabelAttribute>(inherit: false);
var withInheritance = property.GetCustomAttribute<LabelAttribute>(inherit: true);
Console.WriteLine($"{property.Name}: direct={direct?.Text ?? "-"}; with inheritance={withInheritance?.Text ?? "-"}");
}
[AttributeUsage(AttributeTargets.Property, AllowMultiple = false, Inherited = true)]
sealed class LabelAttribute : Attribute
{
public LabelAttribute(string text) => Text = text;
public string Text { get; }
}
class BaseItem
{
[Label("base")]
public virtual string Name => "";
}
sealed class Item : BaseItem
{
public override string Name => "";
public string Code { get; private set; } = "";
[Label("private")]
private string Hidden => "";
[Label("static")]
public static string Kind => "";
}Result
Usage: Property, AllowMultiple=False, Inherited=True Code: direct=-; with inheritance=- Name: direct=-; with inheritance=base
The program reads the usage rules for `LabelAttribute` first, then prints the properties in ordinal name order. `Code` has no label, and the `Name` override finds `base` only with `inherit: true`. The tagged properties `Hidden` and `Kind` do not pass the filter.
Related lessons
- C# · Lesson 24 · Advanced · Version: 3
Sources
- AttributeUsageAttribute Class (System)
- AttributeTargets Enum (System)
- Attributes - C# language specification
- BindingFlags Enum (System.Reflection)
- Type.GetProperties Method (System)
- CustomAttributeExtensions.GetCustomAttribute Method (System.Reflection)
- CustomAttributeExtensions.GetCustomAttributes Method (System.Reflection)
- Attribute.GetCustomAttribute Method (System)
- MemberInfo.GetCustomAttributes Method (System.Reflection)
- CustomAttributeData Class (System.Reflection)