Using the Elvis operator in conjunction with a string.

I wonder why the following code works in C # 6.0:
(In this example, the data is a random class containing val as a public string)

if ("x".Equals(data.val?.ToLower()) { }

But the following line is not like this:

if (data.val?.ToLower().Equals("x")) { }

Visual Studio shows me the following error:

Cannot implicitly convert type to 'bool?' to "bool". Explicit conversion exists (are you skipping listing?)

+4
source share
4 answers
if ("x".Equals(data.val?.ToLower()) { } 

In the end, a boolean will be returned because the call Equals, but this:

if (data.val?.ToLower().Equals("x")) { }

, System.Nullable<bool>, bool ( - , null, true false), if. , # a null false ( #).

+7

# 6.0,

if (data.val?.ToLower().Equals("x") ?? false) { }
+3

Equals, bool?, .

+2

, , , , , .

:

string temp = data.val != null ? data.val.ToLower() : null;
if ("x".Equals(temp)) { }

.

:

bool? temp = data.val != null ? data.val.ToLower().Equals("x") : null;
if (temp) { } //error

This may be less obvious, but the operator data.val?.ToLower().Equals("x")will return nullif data.valis nullotherwise it will return the result data.val.ToLower().Equals("x"). Since the operator can return nullor bool, the type of the whole operator bool?, but you cannot directly use bool?in if.

As others have pointed out, converting bool?to boolwill fix your problem. One way to do this is to use GetValueOrDefault():

if (data.val?.ToLower().Equals("x").GetValueOrDefault()) { }
+1
source

Source: https://habr.com/ru/post/1612765/


All Articles