Is there a way to make the analyzer understand that the variable Bar
has a value for the following case?
#nullable enable
class Foo {
bool GenerateArray => Bar.HasValue;
int? Bar { get; set; }
void FooBar() {
var data = (GenerateArray) ? new int[Bar.Value] : null;
}
}
There is the warning "Nullable value type may be null." for Bar.Value
but it obviously can't be.
I am aware of two ways to avoid the warning. Both have disadvantages:
- Using
Bar.HasValue
directly instead of the propertyGenerateArray
. However usingGenerateArray
improves readability. - Using
Bar!.Value
instead ofBar.Value
. However, if someone changes the code, for instance, by makingGenerateArray
an auto-property in the future, the warning may become relevant again, but won't appear.
The problem here slightly differs from this question, where a local variable was used instead of a property. The accepted answer below works (as soon as C# 9 is released) for the property but not for the local variable, if I understand it correctly. Hence, the question is not a duplicate.
See Question&Answers more detail:os