4

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]?

S Itzik
  • 494
  • 3
  • 12

2 Answers2

3

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.

canton7
  • 37,633
  • 3
  • 64
  • 77
  • @s-itzik this is the answer to your question. – Eriawan Kusumawardhono Mar 21 '20 at 16:26
  • They are also used to let the Migrations subsystem from Entity Framework to know how to model your database tables from your models in a EF CodeFirst scenario. – Steve Mar 21 '20 at 16:31
  • Ok, I understood I missed the purpose :-) So thank you. This way it worked: var context = new ValidationContext(a, serviceProvider: null, items: null); var results = new List(); var isValid = Validator.TryValidateObject(a, context, results); if (!isValid) { foreach (var validationResult in results) { Console.WriteLine(validationResult.ErrorMessage); } } I didn't understand the context issue yet, but you answered my q. – S Itzik Mar 22 '20 at 10:24
1

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