Essential C# Data Annotation  Suggest an edit

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:

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.


Table Of Contents
22 Enum
25 GUID
51 Data Annotation
107 Stream
108 Timers
  ↑ ↓ to navigate     ↵ to select     Esc to close