Farhad Jabiyev
Farhad Jabiyev

Reputation: 26635

?? (null coalescing) vs ? (ternary if) expression

Please, look at that sample code:

short? myNullableShort = 5;
short myShort = 0;

// It works
myShort = myNullableShort ?? 0;

// It doesn't work, Compiler error
// Cannot implicitly convert type 'short?' to 'short'. 
// An explicit conversion exists (are you missing a cast?)  
myShort = myNullableShort != null ? myNullableShort : 0;

I can understand why is the second one not working. But, I would expect that the first one will cause the compiler error, but it isn't.

My question is that, why the first one works fine?

Upvotes: 0

Views: 1198

Answers (2)

user743382
user743382

Reputation:

myNullableShort ?? 0 works like myNullableShort != null ? myNullableShort.Value : 0. That is, the ?:'s middle operand is an expression of type short, not short?.

But if you want to avoid using ??, a more readable way of writing it than with ?: is myNullableShort.GetValueOrDefault(), or the slightly more verbose myNullableShort.GetValueOrDefault(0).

Actually, that myNullableShort.GetValueOrDefault() will be used behind the scenes by the compiler when you write myNullableShort ?? 0: a ?? b gets translated to a.HasValue ? a.GetValueOrDefault() : b, as a micro-optimisation.

Upvotes: 4

Timothy Groote
Timothy Groote

Reputation: 8643

When you reach the line :

myShort = myNullableShort != null ? myNullableShort : 0;

myNullableShort is still a nullable, and you can't cast a nullable to a non-nullable.

try this:

myShort = myNullableShort.HasValue ? myNullableShort.Value : 0;

the first one works because you can assign a nullable a value from a non-nullable, and myNullableShort ?? 0 is guaranteed to return either the value of myNullableShort (if present) or 0

Upvotes: 1

Related Questions