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
should be still considered the not same type, but it works in the situation.
Any advice to this will be appreciated. Thanks.