In this document why would Microsoft show creating a model where required properties are set to null
? I started using this code for all my DTO models where I have required strings but I figured I better find out what it means first. Unfortunately I can’t find anyone talking about this on the web.
Here is how they show creating a model:
public class Movie
{
[Required]
[StringLength(100)]
public string Title { get; set; } = null!;
Why would you say the Title
is required but then default it’s value to null
?
It seems like to me you would normally wright this logic like this:
public class Movie
{
[StringLength(100)]
public string? Title { get; set; }
I guess I’m wondering about 2 issues
- Why would you add the
[Required]
attribute to a nullable property. - When do you use this syntax
{ get; set; } = null!;
?
2
Answers
This is done to prevent the nullability warnings which will be produced by compiler during the null-state analysis (since just calling
new Movie()
will result in nulls assigned to the corresponding properties,!
is so called null-forgiving operator which forces compiler to ignore the warnings).Usually such code comes from assumption that class will be used only as DTO for binding the incoming request and should not be directly instantiated in the code (except for tests).
Note that since C# 11
required
keyword can be used instead of the attribute:Which arguably makes model clearer and robust.
Note that it can have a bit unexpected behavior when used "directly" (ASP.NET Core MVC handles that during binding) with
System.Text.Json
(see Throw exception when missing not nullable value in System.Text.Json).