C#: Non-nullable Property Must Contain A Non-null Value When Exiting Constructor. Consider Declaring The Property As Nullable

This error message is indicating that you have a non-nullable property in a class, but when the constructor exits, the property does not have a non-null value assigned to it.

To resolve this issue, you have a few options:

  1. Assign a non-null value to the property in the constructor:
public class MyClass
{
    public string NonNullableProperty { get; }

    public MyClass(string value)
    {
        NonNullableProperty = value ?? throw new ArgumentNullException(nameof(value));
    }
}
  1. Make the property nullable by adding a question mark (?) after the type declaration:
public class MyClass
{
    public string? NullableProperty { get; }

    public MyClass(string? value)
    {
        NullableProperty = value;
    }
}
  1. If a null value is not expected for this property, you can use the null-forgiving operator (!) to suppress the compiler warning. However, it is generally not recommended to use this operator unless you are certain that the property will never be null.
public class MyClass
{
    public string NonNullableProperty { get; }

    public MyClass(string value)
    {
        NonNullableProperty = value!;
    }
}

By either assigning a non-null value to the property, declaring it as nullable, or using the null-forgiving operator, you can resolve the "Non-nullable property must contain a non-null value when exiting constructor" error.

About the Author Rex

I'm a passionate tech blogger with an insatiable love for programming! From my early days tinkering with code, I've delved into web dev, mobile apps, and AI. Sharing insights and tutorials with the world is my joy, connecting me to a global community of like-minded tech enthusiasts. Python holds a special place in my heart, but I embrace all challenges. Constantly learning, I attend tech conferences, contribute to open-source projects, and engage in code review sessions. My ultimate goal is to inspire the next generation of developers and contribute positively to the ever-evolving tech landscape. Let's code together!