skip to Main Content

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

  1. Why would you add the [Required] attribute to a nullable property.
  2. When do you use this syntax { get; set; } = null!;?

2

Answers


    1. Required is an attribute that does not mean that this property must not be null in the class, but that when processed in MVC, if this property is used and null, an error occurs. That is, the value itself can be null.
    2. null! – sets the property to its default value (string has a default value of null), but the postfix operator ! suppresses warnings related to nullable types
    Login or Signup to reply.
  1. but then default it’s value to null?

    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:

    The required modifier indicates that the field or property it’s applied to must be initialized by an object initializer. Any expression that initializes a new instance of the type must initialize all required members. The required modifier enables developers to create types where properties or fields must be properly initialized, yet still allow initialization using object initializers.

    public class Movie
    {
        [StringLength(100)]
        public required string Title { get; set; }
    }
    

    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).

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search