How do you use reflection to read a custom attribute's values off a property at runtime?
Short answer
Use GetCustomAttribute () (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…
Advertisement
AModel answer
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.
Likely follow-ups
- How would you check whether an attribute exists WITHOUT retrieving its full instance, for a quick presence check?
Related topics