简体   繁体   中英

c# assign value for nullable boolean

I am trying to play around with the ?: Operator on assigning a value into a nullable boolean variable.

This the original code which works fine

bool? result;
var condition = 3;

if (condition == 1)
    result = true;
else if (condition == 2)
     result = false;
else result = null;

After I change the code, it hit an error, and I fix it after searching the internet

// before (error occur)
result = condition == 1 ? true : (condition == 2 ? false : null);

// after (fixed error)
result = condition == 1 ? true : (condition == 2 ? false : (bool?)null); 
// *or
result = condition == 1 ? true : (condition == 2 ? (bool?)false : null);

I understand that both expressions have to be of the same type, but why it only required to convert one expression but not all of the expression? which make me confused.

from my understanding bool and bool? or bool? and null bool? and null should be still considered the not same type, but it works in the situation.

Any advice to this will be appreciated. Thanks.

In a ternary conditional operator, the compiler requires that each of the possible assigned values are of the same type.

In the segment (condition == 2 ? false : null) , the two possible values are false and null . The compiler sees false as a bool , so it will error as null isn't a valid alternate value for a bool .

By prefixing either with (bool?) , you make it clear that you're actually assigning a nullable boolean, making the compiler happy because it knows both values are indeed the same type.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM