Reputation: 6081
I have an event
which returns a boolean
. To make sure the event is only fired if anyone is listening, i call it using the null-conditional operator (questionmark).
However, this means that I have to add the null-conditional operator to the returned boolean as well. And that means that I cannot figure out how to use it in an if-statement afterwards. Does anyone knows how to handle this?
switch (someInt)
{
case 1:
// Validate if the form is filled correctly.
// The event returns true if that is the case.
bool? isValid = ValidateStuff?.Invoke();
if (isValid)
// If passed validation go to next step in form
GoToNextStep?.Invoke();
break;
// There are more cases, but you get the point
(...)
}
Upvotes: 8
Views: 5593
Reputation: 13652
You could use
if (isValid.GetValueOrDefault())
which will give false
if isValid
is null
.
or use the ??
operator
if (isValid ?? false)
which returns the value of the left operand if it is not null
and the value of the right operand otherwise. So basically a shorthand for
if (isValid == null ? false : isValid)
Upvotes: 14
Reputation: 186688
The problem is that in case of Nullable bool?
you have three-valued logic: true
, false
and null
and thus you have to put explicitly if null
should be treated as true
, e.g.:
if (isValid != false) // either true or null
GoToNextStep?.Invoke();
or null
shall be considered as false
:
if (isValid == true) // only true
GoToNextStep?.Invoke();
Upvotes: 3
Reputation: 3515
One option would be to test wether isValid
has a value:
if (isValid.HasValue && (bool)isValid)
Another option is to give isValid
a default value when nobody is listening to your event. This can be done with the null coalescing operator:
bool isValid = ValidateStuff?.Invoke() ?? true; // assume it is valid when nobody listens
Upvotes: 1