© 2026 Hedgehog Software, LLC

TwitterGitHubDiscord
More
CommunitiesDocsAboutTermsPrivacy
Search
Star
Setup for Free
C#C
C#•2y ago•
11 replies
KelTi

"Non-nullable field..." warning even though the value is ensured to be declared

Hi, I am very much a C# beginner so please excuse me if it's a dumb question. I'm learning from the Pro C# book and I have this code:

class Employee
{
    private string _empName;

    public Employee(string name) /*Non-nullable field '_empName' must contain a non-null value when exiting constructor. Consider declaring the field as nullable.*/
    {
        Name = name;
    }

    public string Name
    {
        get { return _empName; }
        set
        {
            if (value?.Length > 15)
            {
                Console.WriteLine("Error! Name cannot exceed 15 characters");
                _empName = String.Empty;
            }
            else
            {
                _empName = value ?? String.Empty;
            }
        }
    }
}
class Employee
{
    private string _empName;

    public Employee(string name) /*Non-nullable field '_empName' must contain a non-null value when exiting constructor. Consider declaring the field as nullable.*/
    {
        Name = name;
    }

    public string Name
    {
        get { return _empName; }
        set
        {
            if (value?.Length > 15)
            {
                Console.WriteLine("Error! Name cannot exceed 15 characters");
                _empName = String.Empty;
            }
            else
            {
                _empName = value ?? String.Empty;
            }
        }
    }
}


The question is - why am I seeing this warning? Inside the property "Name" I'm handling both cases - when the value is null and is not null. In both cases, I'm assigning some string value to the variable _empName, ensuring it doesn't end up as null.

If I changed the _empName declaration to "private string _empName = String.Empty" then the warning goes away. I just don't see the need for that since I've already handled the null-case. Is that the desired behavior of the compiler? Why? Thanks for all the help in advance.
C# banner
C#Join
We are a programming server aimed at coders discussing everything related to C# (CSharp) and .NET.
61,871Members
Resources

Similar Threads

Was this page helpful?
Recent Announcements

Similar Threads

Non-Nullable field (WPF)
C#CC# / help
2y ago
✅ *"Converting possible null value to non nullable type"* warning in `Console.ReadLine()`
C#CC# / help
11mo ago
❔ Non-nullable field 'rating' must contain a non-null value when exiting constructor
C#CC# / help
4y ago
Warning: NULL literal or a possible NULL value is being converted to a non-nullable type.
C#CC# / help
2y ago