Prior to .NET 6, null-state analysis and variable annotations are disabled for existing project, however, it is enabled for all .NET 6 projects by default. Because of which, all the properties or models are showing warning for non-nullable elements.

Recent version of the Visual Studio 2022 and .NET 6, we have a common warning for the models or properties. The warning is given below.

Warning:

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

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 run my .NET 6 application smoothly.

Exact Warning:

Non-nullable property ‘propertyname’ must contain a non-null value 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).

Let’s explore a bit more on nullable references.

Null state Analysis

This analysis highlights and tracks the null reference. In other words, our code may return null response, which may result in runtime error throwing System.NullReferenceException. The .NET compiler utilizes Null State Analysis to identify the null-state of a variable or properties.

To overcome this System.NullReferenceException and resolve this warning, we can assign a default value to the variable. Alternatively, we can check against null before doing any modification or operation. 

Sample:

String rijsat = null;
//code
//code
// warning: dereference null.
Console.WriteLine($"The length of the message is {rijsat.Length}");
if(rijsat != null)
{
// No warning. Analysis determined "message" is not null.
Console.WriteLine($"The length of the message is { rijsat.Length}");
}
rijsat = "Hello, World!";

// No warning. Analysis determined "message" is not null.
Console.WriteLine($"The length of the message is {rijsat.Length}");

This is how static analysis determines that the rijsat is dereference null, i.e. maybe-null. However, if we check null before using it or assign the value, then the warning will be removed.

Null variable Annotations

We generally define the variable to be either null or not null, explicitly with reference type.

We can declare a variable as non-nullable reference type or nullable reference type, which provides clear indication to null-state analysis. Based on the declaration, the compiler gets enough information to make assumptions about the variable.

Nullable Reference Type: we use syntax “?” for nullable value types in variables. By appending ? in the type of the variable, we declare a nullable variable.

Example

string? rijsat;

Using the above declaration, it is verified that all reference type variables in existing code. However, local variables var is considered as nullable.

We can also overwrite a warning if we know the variable is not null. Even though we know that value can’t be null, the compiler detects it as maybe-null with it null-state analysis. We can use null-forgiving operator ! after the variable. To overwrite compiler’s analysis:

Example

rijsat!.Length

Generally, the rules for handling any type of parameter as per C# 8.0.

  • If the type argument for T is a reference type, T? references the corresponding nullable reference type. For example, if T is a string, then T? is a string?.
  • If the type argument for T is a value type, T? references the same value type, T. For example, if T is an int, the T? is also an int.
  • If the type argument for T is a nullable reference type, T? references that same nullable reference type. For example, if T is a string?, then T? is also a string?.
  • If the type argument for T is a nullable value type, T? references that same nullable value type. For example, if T is a int?, then T? is also a int?.

https://docs.microsoft.com/en-us/dotnet/csharp/nullable-references

Solution

Now, we will discuss the solution for the above issue.

We can resolve this error in 3 ways.

Solution 1

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

Sample

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.

Example

public class AppSetting {
    public string ReferenceKey { get; set; } = string.empty;
    public string Value { get; set; } = string.empty;
    public string Description { get; set; } = 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.

<Nullable>enable</Nullable>

https://docs.microsoft.com/en-us/dotnet/csharp/nullable-references#nullable-contexts

These are three ways you can overcome the above warning.

Conclusion

In this article, we have elucidated about nullable references in C# in depth. In .NET 6, there is a common warning related to non-nullable property, and we discussed the reasons behind this. The compiler declares this warning in order to prevent exception throw related with System.NullReferenceException. Furthermore, I have shared various solutions to overcome and resolve the warning.

By Rijwan Ansari

Research and Technology Lead | Software Architect | Full Stack .NET Expert | Tech Blogger | Community Speaker | Trainer | YouTuber. Follow me @ https://rijsat.com 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 c-sharpcorner.com 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.

41 thoughts on “Resolving warning: Non-nullable Property Must Contain a Non-null Value in .NET 6”
  1. Hey there! I realize this is kind of off-topic however I had to ask.
    Does operating a well-established blog like yours require a massive amount work?
    I’m brand new to blogging but I do write in my journal on a daily basis.

    I’d like to start a blog so I can easily share
    my experience and thoughts online. Please let me know if
    you have any suggestions or tips for new aspiring bloggers.
    Thankyou!

  2. Hurrah, that’s what I was searching for, what a stuff!
    existing here at this weblog, thanks admin of this website.

  3. Right here is the perfect webpage for anybody who wishes to understand this
    topic. You know so much its almost tough to argue with you (not
    that I actually will need to…HaHa). You certainly put a new spin on a subject that
    has been written about for decades. Excellent stuff,
    just excellent!

  4. It’s actually a great and useful piece of information. I am glad that you shared this
    useful information with us. Please keep us up to date like this.
    Thanks for sharing.

  5. Your way of explaining the whole thing in this paragraph is genuinely pleasant, every one
    be able to effortlessly understand it, Thanks a lot.

  6. Hey! I just wanted to ask if you ever have any problems with hackers?
    My last blog (wordpress) was hacked and I ended up losing
    many months of hard work due to no backup. Do you have any methods
    to protect against hackers?

  7. I loved as much as you’ll receive carried
    out right here. The sketch is tasteful, your authored material stylish.
    nonetheless, you command get bought an impatience over that you wish
    be delivering the following. unwell unquestionably come more
    formerly again as exactly the same nearly very
    often inside case you shield this increase.

  8. Wow, this paragraph is nice, my younger sister is analyzing these things, so I am going to let know
    her.

  9. First of all I would like to say awesome blog!
    I had a quick question in which I’d like to ask if you don’t mind.
    I was interested to find out how you center yourself and clear your
    head prior to writing. I have had a tough time clearing my thoughts in getting my thoughts out.
    I do take pleasure in writing but it just seems like the first 10
    to 15 minutes are wasted just trying to figure out how to begin. Any recommendations or hints?
    Thanks!

  10. Hi to every body, it’s my first visit of this blog; this web site carries amazing and actually fine stuff
    designed for readers.

  11. We stumbled over here different website and thought I might check things
    out. I like what I see so now i’m following you. Look forward to going over your web page repeatedly.

  12. of course like your web-site however you need to take
    a look at the spelling on quite a few of your posts. Many of them
    are rife with spelling issues and I to find it very bothersome to tell the truth nevertheless I
    will surely come again again.

  13. fantastic post, very informative. I wonder why the opposite specialists of this
    sector do not understand this. You should continue your writing.
    I’m sure, you’ve a huge readers’ base already!

  14. Hey just wanted to give you a quick heads up.

    The text in your post seem to be running off the screen in Ie.

    I’m not sure if this is a format issue or something to
    do with browser compatibility but I thought I’d post
    to let you know. The design look great though! Hope you get the problem resolved soon. Kudos

  15. For newest information you have to pay a quick visit internet and on world-wide-web I found this website as
    a most excellent web page for latest updates.

  16. Howdy, I do believe your website could possibly be having
    web browser compatibility problems. When I look at your website in Safari, it looks fine but when opening
    in IE, it’s got some overlapping issues. I simply wanted to give you a quick

  17. I am regular reader, how are you everybody? This post posted at this website is genuinely good.

  18. Thank you for the аuspicious ѡriteup. It in fact was a amusement ɑccount it.
    Look advanced tⲟ far added agreeable from yoᥙ!
    By the way, how can we communicate?

  19. I am curious to find out what blog platform you’re utilizing?
    I’m experiencing some small security problems with my latest blog and
    I’d like to find something more secure. Do
    you have any suggestions?

  20. hello there and thank you for your information –
    I’ve definitely picked up something new from right here.
    I did however expertise some technical issues using this website, as I experienced to reload the website a lot
    of times previous to I could get it to load properly.
    I had been wondering if your hosting is OK? Not that I am complaining, but sluggish loading instances times will often affect your placement in google and could damage your high-quality score if advertising and marketing with
    Adwords. Anyway I am adding this RSS to my e-mail and can look out for much more of
    your respective fascinating content. Make sure you
    update this again very soon.

  21. This web site really has all of the information and facts I wanted concerning this subject and didn’t know who to ask.

  22. Spot on with this write-up, I actually believe this amazing site needs a great deal more attention.
    I’ll probably be back again to read through more, thanks for the advice!

  23. A person necessarily assist to make seriously articles I might
    state. This is the very first time I frequented your website page and thus far?

    I amazed with the research you made to create this actual post incredible.

    Magnificent task!

  24. This post is tгuly a fastidious one it assists new net
    vіewers, who are wishing in favor of blogging.

  25. I know this if off topic but I’m looking into starting my own weblog and
    was wondering what all is required to get setup? I’m assuming having a blog like yours would cost a pretty penny?

    I’m not very internet savvy so I’m not 100% certain.
    Any recommendations or advice would be greatly appreciated.

    Thanks

  26. of course like your website but you need to take
    a look at the spelling on quite a few of your posts. Many of them
    are rife with spelling issues and I in finding it very troublesome to inform the truth on the other hand I
    will certainly come again again.

  27. I like the helpful info you provide in your articles.
    I’ll bookmark your weblog and check again here frequently.

    I am quite sure I’ll learn a lot of new stuff right here!
    Best of luck for the next!

  28. It’s actually very complicated in this busy life to listen news
    on TV, therefore I only use web for that purpose, and obtain the
    newest information.

  29. Hi all, here every one is sharing such familiarity, thus it’s
    pleasant to read this blog, and I used to go to see this blog everyday.

  30. It is not my first time to go to see this web
    site, i am browsing this website dailly and take good facts from here every day.

  31. I was wondering if you ever thought of changing the page layout of your
    blog? Its very well written; I love what youve got
    to say. But maybe you could a little more in the way of content so people could connect with
    it better. Youve got an awful lot of text for only having 1
    or 2 images. Maybe you could space it out better?

  32. If you are going for best contents like myself, just visit this website daily for the reason that it
    presents quality contents, thanks

  33. With havin so much written content do you ever run into any issues
    of plagorism or copyright infringement? My site has a lot of exclusive content I’ve either
    created myself or outsourced but it looks like a lot of it is popping it
    up all over the internet without my permission. Do you know any methods
    to help stop content from being stolen? I’d definitely appreciate
    it.

Leave a Reply

Your email address will not be published. Required fields are marked *