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.

 

作者:Chuck Lu    GitHub    
posted @   ChuckLu  阅读(276)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 全程不用写代码,我用AI程序员写了一个飞机大战
· DeepSeek 开源周回顾「GitHub 热点速览」
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· 记一次.NET内存居高不下排查解决与启示
· 白话解读 Dapr 1.15:你的「微服务管家」又秀新绝活了
历史上的今天:
2020-02-20 HearthBuddy combo
2019-02-20 Model Validation in ASP.NET Web API
2019-02-20 Environment.NewLine
2019-02-20 What's the difference between SDK and Runtime in .NET Core?
2019-02-20 The current .NET SDK does not support targeting .NET Core 3.0
2019-02-20 CCleaner如何禁用开机自动启动
2017-02-20 GridColumn (Column Layout and Auto Width)
点击右上角即可分享
微信分享提示