C# Language Data Annotation Basics


Data annotations are a way of adding more contextual information to classes or members of a class. There are three main categories of annotations:

  • Validation Attributes: add validation criteria to data
  • Display Attributes: specify how the data should be displayed to the user
  • Modelling Attributes: add information on usage and relationship with other classes


Here is an example where two ValidationAttribute and one DisplayAttribute are used:

class Kid
    [Range(0, 18)] // The age cannot be over 18 and cannot be negative
    public int Age { get; set; }
    [StringLength(MaximumLength = 50, MinimumLength = 3)] // The name cannot be under 3 chars or more than 50 chars
    public string Name { get; set; }
    [DataType(DataType.Date)] // The birthday will be displayed as a date only (without the time)
    public DateTime Birthday { get; set; }

Data annotations are mostly used in frameworks such as ASP.NET. For example, in ASP.NET MVC, when a model is received by a controller method, ModelState.IsValid() can be used to tell if the received model respects all its ValidationAttribute. DisplayAttribute is also used in ASP.NET MVC to determine how to display values on a web page.