I wonder why the following code works in C# 6.0:
(In this example data is a random class containing val as a public string)
if ("x".Equals(data.val?.ToLower()) { }
But the following line isn't:
if (data.val?.ToLower().Equals("x")) { }
Visual Studio shows me the following error:
Cannot implicitly convert type 'bool?' to 'bool'. An explicit conversion exists (are you missing a cast?)
if ("x".Equals(data.val?.ToLower()) { }
Will eventually return a boolean because the of Equals
call but this:
if (data.val?.ToLower().Equals("x")) { }
when the expression is evaluated it will return a System.Nullable<bool>
which is different than a bool
(former is a struct that can be assigned the value null
while the latter can only be true
or false
) the the if
expects. Also, in C# a null
value doesn't evaluate to false (according to the C# specification).
I don't have c# 6.0 to test but this should work
if (data.val?.ToLower().Equals("x") ?? 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