✅ required attribute vs [Required] annotation
Hello guys, I was just reading a bit about the
required
modifier and [Required]
data annotation. From what I've understood, required
make sure something is not null at compile time itself whereas the data annotation one make sure something is not null at runtime. Beside these 2, are there other differences? Also, I was wondering, why not just stick to required
, are there any use cases where one is better than the other please.5 Replies
[Required]
doesn't ensure anything except if you're using something like ASP.NET or Entity Framework which care about it
required
ensures that a field/property is set through the object initializer when an object is createdoh ok I see, the thing is, I was using the EF core, I wanted a particular field to be non-nullable in a database using code first approach. At first I used the [Required] data annotation but then switched to required instead. Here it doesn't matter which one I use, no? Like the field would still be non-nullable whether I use [Required] or required ?
I haven't used EF enough to know, I'm not sure whether it actually cares about
required
or notYeah I think it does care, I tested it, the field is non-nullable when used but I guess in this case [Required] would also have the same impact
it cares