Why does Visual Studio thing my document type property is nullable when the property is made "manditory" in the backoffice?

This is probably a limitation of my understanding of the inter-workings of Umbraco so it is going to sound a bit stupid and I am asking here as I am trying to break my dependency on just asking AI for everything and go back to old school questions and research.

I dug around as best as I could but did not see anything. I have a property “headline” on my “News Article” document type. I have marked this property as “Field is mandatory” under the “Validation” configuration of the property.

I am now writing a C# method against this document type to do some parsing. I go to assign the value of “headline” to a ViewModle’s property public required string Headline { get; set; } but Visual Studio is warning me that the document type’s proper is “not nullable aware” and I have a “possible null reference assignment”.

This is the code I am using to assing/process some of the aticle information into the ViewModel:

IReadOnlyList<NewsArticleSnippetVM> newsArticles = articles.Select(x => new NewsArticleSnippetVM
{
    Headline = x.Headline,
    AuthorBiographyPageUrl = "null",
    AuthorName = "null",
    HeadlineImageUrl = "null",
    ArticleSnippet = CreateArticleSnippet(x.Article.ToString()),
    ArticleUrl = x.Url()
}).ToList();

Please ignore the null value assignments for some properties, I just have not figure out how to do those assignments yet.

I personally would have though that if a property is marked as “mandatory” then it would not be nullable at the code level.

Hi @Eaglef90

Models Builder marks every reference-type property as nullable because it doesn’t take validation into account. Mandatory is a backoffice thing, and even there it only stops you publishing. You can still save a draft with the field empty, including via the API.

Simplest fix is to fall back to an empty string:

Headline = x.Headline ?? String.Empty,

Or you can tell the compiler it’s never null, but that’s a bit of a risk:

Headline = x.Headline!,

Justin

On top of that, if you have a property that not required and you make that property required afterwards, the already published content doesn’t suddenly get a value and would still be null. So you always need to null check every property.

So do what @justin-nevitech mentioned or use a if statement to conditionally render some html. I would never supress it.

I had not taken into account those scenarios. Thanks for explaining everything.