Home » C# » Non-nullable property ‘name’ must contain a non-null value…

Non-nullable property ‘name’ must contain a non-null value…

By Emily

If you’re coding in .Net Core you’ve probably come across an error about ‘a non-nullable property’ that says something like this :

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

What does the Non-nullable property message mean?

The compiler is warning you that the default assignment of your property is incorrect – or rather that it doesn’t match the default state for that type of property.

For instance if your property is a String, then it’s default state is an empty string – String.Empty or "".

Why do I see the Non-nullable property message?

If you’re seeing this warning message then you haven’t assigned a default empty String value to it when it’s declared, and/or have not defined it as nullable.

You’ll only see this message if nullable reference types are switched on. This setting changes all reference types to be non-null, unless stated otherwise with a ?.

This code would trigger the warning message because you’ve defined a string property, but it is not nullable and has not been assigned a string value:

public class Product
{
	//this will produce the error message - "Non-nullable 
  	//property 'Name' must contain a non-null value ...."
 	public string Name {get; set;} 
}

How to fix the problem

There are a number of ways you can fix this problem. One is to suppress the warning message but in general it’s a bad idea to do this! Instead you can use one of the following methods to stop the warning message.

Declare the property as nullable

Declaring the property as a nullable string instead will mean you will no longer see the message:

public class Product
{
  	//make the property nullable by using string?
	public string? Name {get; set;} 
}

Declare the property with a default assignment in-line

You could also declare the property with defaults in-line :

public class Product
{
    public string Name {get; set;} = string.Empty;
 }

Assign a value to the property in the constructor

Consider the second part of the warning message – must contain a non-null value when exiting constructor. Another way of dealing with the issue is to assign defaults to your properties in the constructor.

public class Product
{
  	//constructor
  	public Product(){
      	Name = string.Empty;
    }

	public string Name {get; set;} 
}

Summary

If you google this issue you will find plenty of people suggesting that to resolve these messages you should go and switch off the nullable reference types warning messages in your project settings. I really wouldn’t recommend doing this!

The messages are there for a reason – much better to try and understand the warning messages and get into the habit of declaring properties correctly, than switch the warnings off and have errors in the application function later on.