Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Operator '||' cannot be applied to operands of type 'bool?' and 'bool?'

I want to check if one of two strings contains a partial string. Knowing that firstString or secondString can be null, I tried the following:

 string firstString= getValue();
 string secondString= getValue();

 if (firstString?.Contains("1") || secondString?.Contains("1"))
   {
     //logic
   }

I am getting a compile time error mentioning that:

Operator '||' cannot be applied to operands of type 'bool?' and 'bool?'

Seems like result of String?.Contains("1") is nullable boolean.

This error actually does make sense to me because running time might face:

{null||true, null||false, null||null, etc..}

What is the best way to override this error? can I avoid writing two nested ifs?

like image 656
Yahya Hussein Avatar asked Feb 13 '18 11:02

Yahya Hussein


1 Answers

It depends how you want to evaluate a null value: as true or false. I am used to false.

If so, you can use the null-coalescing operator:

(firstString?.Contains("1") ?? false) || (secondString?.Contains("1") ?? false)
like image 73
Patrick Hofman Avatar answered Oct 23 '22 04:10

Patrick Hofman