Recently, I was getting this warning for most of the properties which are not specified as nullable. I was not happy this warning, though I was able to run my .NET 6 application smoothly.

Exact Error:

Non-nullable property ‘propername’ must contain a non-nullvalue when exiting constructor. Consider declaring the property as nullable

After carefully observing this error message, it makes sense for those properties. In order to minimize the likelihood that our code causes the runtime to throw System.NullReferenceException, we need to resolve this warning.

Therefore, the compiler is giving warning in the solution that the default assignment of your properties (which is null) doesn’t match its state type (which is non-null string).

We can resolve this error in 3 ways.

Solution 1

We can simply make the properties nullable, as shown below:

public class AppSetting {
    public string? ReferenceKey { get; set; }
    public string? Value { get; set; } 
    public string? Description { get; set; }

Solution 2

We can assign default value to those properties as shown below:

public class AppSetting {
    public string ReferenceKey { get; set; } = “Default Key”;
    public string Value { get; set; } = “Default Value”;
    public string Description { get; set; } = “Default Description”;

Alternatively, you can give a reasonable default value for non-nullable strings as string.empty.

Solution 3

You can disable this warning from project level. You can disable by removing the below line from project file csproj or setting. 



These are three ways you can overcome the above warning.

Kind Regards

By Rijwan Ansari

Research and Technology Lead | Software Architect | Full Stack .NET Expert | Tech Blogger | Community Speaker | Trainer | YouTuber. Follow me @ Md Rijwan Ansari is a high performing and technology consultant with 10 plus years of Software Development and Business Applications implementation using .NET Technologies, SharePoint, Power Platform, Data, AI, Azure and cognitive services. He is also a Microsoft Certified Trainer, C# Corner MVP, Microsoft Certified Data Analyst Associate, Microsoft Certified Azure Data Scientist Associate, CSM, CSPO, MCTS, MCP, with 15+ Microsoft Certifications. He is a research and technology lead in Tech One Global as well as leading Facebook community Cloud Experts Group and SharePoint User Group Nepal. He is a active contributor and speaker in community, C# Corner MVP and his rank at 20 among 3+ millions members. Additionally, he is knee to learn new technologies, write articles, love to contribute to the open-source community. Visit his blog RIJSAT.COM for extensive articles, courses, news, videos and issues resolution specially for developer and data engineer.

2 thoughts on “Non-nullable property must contain a non-null value when exiting constructor. Consider declaring the property as nullable.”

Leave a Reply

Your email address will not be published.