C# – Implicit Casting of Null-Coalescing Operator Result

c++implicit-conversionnull-coalescing-operatornullable

With the following understanding about null coalescing operator (??) in C#.

int? input = -10;
int result = input ?? 10;//Case - I
//is same as:
int result = input == null? input : 10; // Case - II

While, by definition and usage, Case I and Case II are same.

It is surprising to see that in Case-I compiler is able to implicitly cast int? to int while in Case-II it shows error: 'Error 1 Cannot implicitly convert type 'int?' to 'int'"

What is it that I am missing about null-coalescing operator?

Thanks for your interest.

Best Answer

To make the second case work with the ternary operator, you could use the following:

int result = input != null ? input.Value : 10;

The Value property of the Nullable<T> type returns the T value (in this case, the int).

Another option is to use Nullable<T>.HasValue:

int result = input.HasValue ? input.Value : 10;

The myNullableInt != null construct is only syntactic sugar for the above HasValue call.