Non-nullable property must contain a non-null value when exiting constructor. Consider declaring the property as nullable
Non-nullable property must contain a non-null value when exiting constructor. Consider declaring the property as nullable
回答1
If you don't want this, you can disable this by deleting the below line from the csproj file or setting it as disable
. By default value is disable
.
<Nullable>enable</Nullable>
Here is the official documentation.
回答2
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.