KelTi
KelTi
CC#
Created by KelTi on 6/9/2024 in #help
"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:
c#
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;
}
}
}
}
c#
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.
12 replies