If a nullable property gets used in the Execute
part of a RelayCommand, and that property is already checked against null in the CanExecute
method, what is the proper way to handle the CS8602: Possible dereference of null
warning for the property?
[ObservableProperty, NotifyCanExecuteChangedFor(nameof(FooCommand)]
private FooType? _fooObject;
[RelayCommand(CanExecute = nameof(CanExecuteFooCommand)]
private void Foo()
{
SomeMethod(FooObject.ID); // gives CS8602: Possible dereference of null
}
private bool CanExecuteFooCommand()
{
return FooObject is not null;
}
private void SomeMethod(FooType? fooObject)
{
}
Which of the ways would you consider the correct way?
Another null check of FooObject
in Execute
?
Use of nullable type ?
in SomeMethod(FooObject?.ID)
Use of the null forgiving operator !
in SomeMethod(FooObject!.ID)
Or is there any other way i don’t know of?
Could FooObject
ever become null in between the CanExecute
and Execute
part?
bil-bal is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.