stringreference-typec#-11.0

Why do I get "CS8618: Non-nullable property must contain a non-null value when exiting constructor" on a string property?


Correct me if I'm wrong, but I thought that strings are, and always have been, a reference type in C#. And if this is still true in C# 11, why do I get CS8618: Non-nullable property must contain a non-null value when exiting constructor on the following code:

public partial class MyClass : SomeOtherClass {
    // Generates CS8618
    private string _userInitials { get; set; } 
}

I've been searching SO and Google for an hour but can't seem to find any logical reason for this. MTIA :-)


Solution

  • Strings ARE a reference type, which means they can be null. Without a constructor, your string property will be initialized to null. Unless the parameter is declared nullable (that is, private string? _userInitials), that's not allowed.

    They have only recently changed things so having null in a reference type is not allowed unless it declared nullable:

    https://learn.microsoft.com/en-us/dotnet/csharp/nullable-migration-strategies