When working with nullable booleans and using null condiional operator could be wrong:
Let's take the follwoing example:
bool? isRecording = savedInstanceState?.GetBoolean("isRecording");
if (isRecording)
- This won't compile. need another approach.
The condition if (isRecording == false)
will be true when the variable is equal to false and when it is null
.
It's logical to work like that since the default value of bool
is false
and the null
value is more suitable to false
.
But we should be careful if the logic need to be executed only if it's equal to false.
Another example:
bool? automaticPaymentEnabled = myService?.GetInput("...") // null;
if (automaticPaymentEnabled == false)
{
RemovePayments(UserId);
}
else
{
SetUpPayments(UserID);
}
If the user has alredy using automatic payments this logic could remove them in case mySerice
is null
.
myService
will be null in certain cases, because its initialization is too slow and takes a lot of resources.
The recommended approach is
if (automaticPaymentEnabled.HasValue)
{
if (automaticPaymentEnabled.Value)
{
// ..enabled
}
else
{
// .. disabled
}
}
// no value
If it doesn't care whether the value is false
or it's not provided, the conditional could be simplified:
if (automaticPaymentEnabled.HasValue && automaticPaymentEnabled.Value)
{
// do enabled stuff
}
else
{
// value not provided or it is false
}