C# Language Data Annotation Data Annotation Basics

Help us to keep this website almost Ad Free! It takes only 10 seconds of your time:
> Step 1: Go view our video on YouTube: EF Core Bulk Extensions
> Step 2: And Like the video. BONUS: You can also share it!

Example

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

Usage

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.



Got any C# Language Question?