Consider the following code:
#nullable enable
class Foo
{
public string? Name { get; set; }
public bool HasName => Name != null;
public void NameToUpperCase()
{
if (HasName)
{
Name = Name.ToUpper();
}
}
}
On the Name=Name.ToUpper() I get a warning that Name is a possible null reference, which is clearly incorrect. I can cure this warning by inlining HasName so the condition is if (Name != null).
Is there any way I can instruct the compiler that a true response from HasName implies a non-nullability constraint on Name?
This is important because HasName might actually test a lot more things, and I might want to use it in several places, or it might be a public part of the API surface. There are many reasons to want to factor the null check into it's own method, but doing so seems to break the nullable reference checker.
HasValue
on a nullable type, not check it againstnull
. It probably doesn't affect your problem though. – Isogamy#nullable disable
then#nullable enable
orrestore
again afterwards (learn.microsoft.com/en-us/dotnet/csharp/…). – Grassgreen!
operator.if(HasName) { Name = Name!.ToUpper(); }
– Eyebrow