Skip to content

Instantly share code, notes, and snippets.

@M-Yankov
Created February 24, 2022 19:15
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save M-Yankov/ad8449b6c289824fe4f42f6816920495 to your computer and use it in GitHub Desktop.
Save M-Yankov/ad8449b6c289824fe4f42f6816920495 to your computer and use it in GitHub Desktop.
An article for my blog

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
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment