Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using Elvis operator in combination with string.Equals

Tags:

c#

.net

c#-6.0

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

like image 450
Mike Limburg Avatar asked Dec 10 '22 20:12

Mike Limburg


2 Answers

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

like image 62
Nasreddine Avatar answered Dec 14 '22 22:12

Nasreddine


I don't have c# 6.0 to test but this should work

if (data.val?.ToLower().Equals("x") ?? false) { }
like image 27
Fredou Avatar answered Dec 14 '22 22:12

Fredou