C# [Required()] annotation doesn't throw exception when it should

Viewed 687

I'm using [Required()] above a property in a simple class:

public class A
{
    [Required()]
    public string Str { get; set; }

    public int Salary { get; set; }
}

In Main(), I create an instance of the class, WITHOUT setting the property:

static void Main(string[] args)
{
    A a = new A();
}

I expected to get an exception, because I didn't set any value to Str property, but I don't get any. Did I miss the purpose of [Required]?

2 Answers

Did I miss the purpose of [Required]?

Very much so. Let's read the docs:

The RequiredAttribute attribute specifies that when a field on a form is validated, the field must contain a value

So we're talking about validation specifically: it's part of the various classes inside the System.ComponentModel.DataAnnotations namespace, which are mostly to do with valiation.

Principally, look at the Validation class, which lets you validate the properties on an object, according to the attributes you've put on them. This infrastructure is used in various places, such as in ASP.NET, or EF.

The Required attribute is for validation (e.g. in ASP.NET), not for throwing runtime exceptions.

Related