Search code examples
c#nullable-reference-types

required keyword or [Required] DataAnnotation


Got this class

using System.ComponentModel.DataAnnotations;

public class SearchQuery 
{
   [Required]
   public string SearchText { get; set; } = null!
}

Wondering if it could be written like this ?

public class SearchQuery 
{   
   public required string SearchText { get; set; }
}

Is the =null! just a old way of doing the required keyword?


Solution

  • They are not the same.

    The required modifier indicates that the field or property it's applied to must be initialized by an object initializer. Meaning you will get error when if not initilised when creating the object. Also required members must be initialized, but they may be initialized to null.

    [Required] attribute specifies that when a field on a form is validated, the field must contain a value. (But does not add constraint on initialization)

    null! is the null forgiving operator you can read more here from another answer.