Why isn't this working?
bool? value = (1==2 ? true : null);
This works just fine:
bool? value = null;
or
bool? value = true;
Why isn't this working?
bool? value = (1==2 ? true : null);
This works just fine:
bool? value = null;
or
bool? value = true;
You have to explicitly cast on of the return type to bool? like:
bool? value = (1 == 2 ? (bool?)true : null);
Or
bool? value = (1 == 2 ? true : (bool?)null);
Either the type of first_expression and second_expression must be the same, or an implicit conversion must exist from one type to the other.
Since there is no implicit conversion available between bool (true) and null, you get the error.
When you're using a ternary operator, both sides of the colon have to be the same type:
var value = (1 == 2 ? true : (bool?)null);
This only applies to value types, since a value type cannot be implicitly converted to null (hence the need for nullable bool, nullable int, etc).
int groupId = (userId == 7) ? 5 : null; // invalid
int groupId = (userId == 7) ? 5 : (int)null; // valid
It's okay to use null by itself on the other side of a reference type, which can be null:
string name = (userId == 7) ? "Bob" : null; // valid
MyClass myClass = (userId == 7) ? new MyClass() : null; // valid