In the below code, why does the compiler null-state analysis fails to deduce that Age
is not null
and warning is produced? Even though the “if” explicitly verifies that. What would be the recommended way to resolve this warning here?
public class Person
{
public double? Age { get; set; }
}
public class Dog
{
public Person Owner { get; set; }
}
public string GetOwnerAgeAsString(Dog dog)
{
if ((dog.Owner != null) && (dog.Owner.Age != null))
return dog.Owner.Age.ToString(); // <-- CS8603: Possible null reference return
return "Unknown";
}
Surprisingly, adding the null-forgiving operator return dog.Owner.Age!.ToString();
doesn’t solve the warning either.
Do I miss something basic here or is it a compiler bug?
(Using VS 17.10.1)