Back to results for “Dependency injection”
C# › Attributes & Reflection

How do you create a custom attribute class, and what does AttributeUsage control?

Intermediate

Answer

Define a class that inherits from System.Attribute (conventionally suffixed with "Attribute", though C# lets you omit the suffix when applying it); the [AttributeUsage] attribute on that class restricts WHICH code elements it can be applied to (class, method, property, etc.) and whether it can be applied multiple times to the same element.
[AttributeUsage(AttributeTargets.Property, AllowMultiple = false)]
public class RequiredAttribute : Attribute {
  public string ErrorMessage { get; set; } = "This field is required.";
}

public class User {
  [Required(ErrorMessage = "Name is mandatory")]
  public string Name { get; set; } = "";
}
Real-world example Building a lightweight custom validation attribute system for a domain model, similar in spirit to DataAnnotations.

Common follow-ups: What does 'AllowMultiple = true' allow you to do that's normally disallowed?