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
(...)
}
This operator (?.) verifies null ability of the operand before calling the method or property. Syntax and usage of null conditional operator (?.) : It uses a question mark ? and member access operator . (the dot) as follows.
Now it is clearly visible that we have to satisfy both of the conditions in order to return null. Fortunately, you still can use one-liner and have a bug-free code, the one thing which is needed is an additional null-coalescing operator in the if statement.
bool someBoolean = true; if (someBoolean) { // Do stuff. } Because if statements evaluate Boolean expressions, what you are attempting to do is an implicit conversion from Nullable<bool>. to bool. Nullable<T> does provide a GetValueOrDefault method that could be used to avoid the true or false comparison.
Because if statements evaluate Boolean expressions, what you are attempting to do is an implicit conversion from Nullable<bool>. to bool. Nullable<T> does provide a GetValueOrDefault method that could be used to avoid the true or false comparison.
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 ? isValid : false)
You can use this:
if (isValid.HasValue && isValid.Value)
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With