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?
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)
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