1

Why isn't this working?

bool? value = (1==2 ? true : null);

This works just fine:

bool? value = null;

or

bool? value = true;
user3595338
  • 737
  • 3
  • 11
  • 26

2 Answers2

4

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

See Conditional Operator C#

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.

Habib
  • 219,104
  • 29
  • 407
  • 436
1

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
Grant Winney
  • 65,241
  • 13
  • 115
  • 165