Nullable reference type in C#8 when using DTO classes with an ORM

The next solution is recommended by EF Core & EF6 see

1) By initializing to null! with forgiving operator

public string ServiceUrl { get; set; } = null! ;
//or
public string ServiceUrl { get; set; } = default! ;

2) Using backing field:

        private string _ServiceUrl;
        public string ServiceUrl
        {
            set => _ServiceUrl = value;
            get => _ServiceUrl
                   ?? throw new InvalidOperationException("Uninitialized property: " + nameof(ServiceUrl));
        }



If it's non nullable, then what can the compiler do when the object is initialized?

The default value of the string is null, so you will

  1. either need to assign a string default value in the declaration

    public string ServiceUrl { get; set; } = String.Empty;

  2. Or initialize the value in the default constructor so that you will get rid of the warning

  3. Use the ! operator (that you can't use)

  4. Make it nullable as robbpriestley mentioned.


Another thing that might come handy in some scenarios:

[SuppressMessage("Compiler", "CS8618")]

Can be used on top of member or whole type.


Yet another thing to consider is adding #nullable disable on top of file to disable nullable reference for the whole file.