Custom Attributes in C#?
Real Use Cases
- Validation frameworks
- Logging metadata
- Role-based security
- API documentation metadata
Custom Attribute Example
[AttributeUsage(AttributeTargets.Property)]
public class RequiredAttribute : Attribute {}
Usage Example
public class Employee
{
[Required]
public string Name { get; set; }
}
Validation Logic
public static void Validate(object obj)
{
var properties = obj.GetType().GetProperties();
foreach (var prop in properties)
{
var isRequired = prop.GetCustomAttributes(typeof(RequiredAttribute), false).Any();
if (isRequired && prop.GetValue(obj) == null)
throw new Exception($"{prop.Name} is required");
}
}