Coder Perfect

Because there is no implicit conversion between ‘int’ and ‘null>, the type of conditional expression cannot be established.


I’m not sure why this isn’t working.

int? number = true ? 5 : null;

Asked by davidhq

Solution #1

According to the specification (7.14), there are three alternatives for the conditional phrase b? x: y: either x and y both have a type and certain good conditions are met, only one of x and y has a type and certain good circumstances are met, or a compile-time error occurs. “Under certain good conditions,” we indicate that some conversions are conceivable, which we’ll go over in detail later.

Let us now go on to the meat of the specification:

The problem is that in this case,

int? number = true ? 5 : null;

There is only one type among the conditional results. In this case, x is an int literal, while y is null, which has no type and is not implicitly convertible to an int1. As a result, “certain good criteria” aren’t met, resulting in a compile-time error.

There are two solutions to this problem:

int? number = true ? (int?)5 : null;

We’re back to the situation where only one of x and y has a type. Although null still lacks a type, the compiler will not have any issues because (int?)5 and null are both implicitly convertible to int? (6.1.4 and 6.1.5).

Obviously, there’s another route:

int? number = true ? 5 : (int?)null;

However, we must now examine a different clause in the specification to understand why this is acceptable:

In this case, x is an int and y is an int? There is no implicit conversion from int to int?, while there is one from int to int? So, the expression’s type is int?

1: It’s also worth noting that the left-hand side’s type is ignored when establishing the type of the conditional expression, which is a common source of misunderstanding.

Answered by jason

Solution #2

Null has no discernible type; all it takes is a little nudging to make it happy:

int? number = true ? 5 : (int?)null;

Answered by Marc Gravell

Solution #3

This is now allowed in C# 9.

Person person = student ?? customer; // Shared base type
int? result = b ? 0 : null; // nullable value type

Or your example:

// Allowed in C# 9.
int? number = true ? 5 : null;

Answered by WBuck

Solution #4

The 5 is an int, as others have pointed out, and null cannot be implicitly converted to an int.

Other options for resolving the problem include:

int? num = true ? 5 : default(int?);
int? num = true ? 5 : new int?();

int? num = true ? 5 : null as int?;
int? num = true ? 5 : (int?)null;

int? num = true ? (int?)5 : null;
int? num = true ? 5 as int? : null;

int? num = true ? new int?(5) : null;

You may alternatively use Nullableint> wherever int? is used.

Answered by Andrew

Post is based on