Search code examples
c#visual-studio.net-core.net-6.0c#-10.0

Non-nullable property must contain a non-null value when exiting constructor. Consider declaring the property as nullable


I have a simple class like this.

public class Greeting
{
    public string From { get; set; }
    public string To { get; set; } 
    public string Message { get; set; }
}

Strangely I get the following warning.

Severity Code Description Project File Line Suppression State Warning CS8618 Non-nullable property 'From' must contain a non-null value when exiting constructor. Consider declaring the property as nullable. MxWork.Elsa2Wf.Tuts.BasicActivities
D:\work\MxWork\Elsa2.0WfLearning\MxWork.Elsa2.0Wf.Tuts\src \MxWork.Elsa2Wf.Tuts.BasicActivities\Messages\Greeting.cs 5 Active

I am baffled at these messages. I got them from all the three properties, and this has suddenly appeared.

visual studio warning message

Can some one please suggest how this can be mitigated?


Solution

  • The compiler is warning you that the default assignment of your string property (which is null) doesn't match its stated type (which is non-null string).

    This is emitted when nullable reference types are switched on, which changes all reference types to be non-null, unless stated otherwise with a ?.

    For example, your code could be changed to

    public class Greeting
    {
        public string? From { get; set; }
        public string? To { get; set; } 
        public string? Message { get; set; }
    }
    

    to declare the properties as nullable strings, or you could give the properties defaults in-line or in the constructor:

    public class Greeting
    {
        public string From { get; set; } = string.Empty;
        public string To { get; set; } = string.Empty;
        public string Message { get; set; } = string.Empty;
    }
    

    if you wish to retain the properties' types as non-null.