C# Interview Question #139
What are custom attributes, and how can they be read with reflection?
Reflection, Dynamic & Runtime Senior Advanced
Quick Interview Answer
A custom attribute is a developer-defined metadata type derived from System.Attribute.
Detailed Explanation
A custom attribute is a developer-defined metadata type derived from System.Attribute.
Attributes can describe classes, methods, properties, parameters, and other code elements. Reflection can inspect those attributes at runtime.
Custom attributes are useful for declarative metadata such as mapping rules, authorization information, validation hints, auditing markers, or framework conventions.
Code Example
[AttributeUsage(AttributeTargets.Class)]
public sealed class AuditableAttribute : Attribute
{
}
[Auditable]
public class Product
{
}
bool auditable = typeof(Product)
.IsDefined(typeof(AuditableAttribute), inherit: true);