C# › Attributes & Reflection
How do you use reflection to read a custom attribute's values off a property at runtime?
IntermediateAnswer
Use GetCustomAttribute<T>() (or GetCustomAttributes for multiple) on a PropertyInfo, MethodInfo, or Type object to retrieve an instance of the applied attribute, then read its properties normally — this is the core mechanism behind validation libraries, serializers, and ORMs that inspect your classes' decorations.
var properties = typeof(User).GetProperties();
foreach (var prop in properties) {
var required = prop.GetCustomAttribute<RequiredAttribute>();
if (required != null) {
Console.WriteLine($"{prop.Name}: {required.ErrorMessage}");
}
}Real-world example Building a simple validation engine that scans a model's properties for [Required] attributes and reports errors.