using coalescing null operator on nullable types changes implicit type

巧了我就是萌 提交于 2019-12-01 15:12:29

Your first two examples are leading you astray; better would be to consider not your

var dateTimeNullable1 = nullableDateTime.HasValue 
    ? nullableDateTime 
    : DateTime.Now;

but rather

var dateTimeNullable1 = nullableDateTime.HasValue 
    ? nullableDateTime.Value 
    : DateTime.Now;

To quote section 7.12 "The null coalescing operator" of the C# 3.0 spec (apologies for slightly ropey formatting):

The type of the expression a ?? b depends on which implicit conversions are available between the types of the operands. In order of preference, the type of a ?? b is A0, A, or B, where A is the type of a, B is the type of b (provided that b has a type), and A0 is the underlying type of A if A is a nullable type, or A otherwise.

So if a is Nullable<Something>, and b can be implicitly converted to Something, the type of the whole expression will be Something. As @Damien_The_Unbeliever suggests, the point of this operator is to coalesce nulls!

To go all language lawyer, for a moment. From the C# spec (version 4):

7.13

The type of the expression a ?? b depends on which implicit conversions are available on the operands. In order of preference, the type of a ?? b is A0, A, or B, where A is the type of a (provided that a has a type), B is the type of b (provided that b has a type), and A0 is the underlying type of A if A is a nullable type, or A otherwise.

So, ?? is explicitly defined to prefer the underlying type of the first expression, if that first expression is a nullable type.

Whereas the language from 7.14 (dealing with ?:) only discusses the actual types of x and y, from the form b ? x : y, and discusses implicit conversions between these two types.

If an implicit conversion (§6.1) exists from X to Y, but not from Y to X, then Y is the type of the conditional expression

Since Nullable(T) defines an implicit conversion from T to Nullable(T), and only an explicit conversion from Nullable(T) to T, the only possible type of the overall expression is Nullable(T).

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!