The null coalescing operator
От: ie Россия http://ziez.blogspot.com/
Дата: 20.09.06 08:53
Оценка:
Помогите разобраться. Есть такой код:

    int? i1 = 1;
    int? i2 = 2;
    int? inull = null;

    Console.WriteLine("(i1 ?? i2) : " + (i1 ?? i2).GetType()); // System.Int32
    Console.WriteLine("(i1 ?? inull) : " + (i1 ?? inull).GetType()); // System.Int32
    Console.WriteLine("(inull ?? i2) : " + (inull ?? i2).GetType()); // System.Int32
    Console.WriteLine("(inull ?? inull) : " + (inull ?? inull).GetType()); // Exception: System.NullReferenceException


По спецификации:

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, and A0 is the type that results from removing the trailing ? modifier, if any, from A. Specifically,
a ?? b is processed as follows:
• If A is not a nullable type or a reference type, a compile-time error occurs.
• If A is a nullable type and an implicit conversion exists from b to A0, the result type is A0. At run-time, a
is first evaluated. If a is not null, a is unwrapped to type A0, and this becomes the result. Otherwise, b is
evaluated and converted to type A0, and this becomes the result.

• Otherwise, if an implicit conversion exists from b to A, the result type is A. At run-time, a is first
evaluated. If a is not null, a becomes the result. Otherwise, b is evaluated and converted to type A, and
this becomes the result.
• Otherwise, if an implicit conversion exists from A0 to B, the result type is B. At run-time, a is first
evaluated. If a is not null, a is unwrapped to type A0 (unless A and A0 are the same type) and converted
to type B, and this becomes the result. Otherwise, b is evaluated and becomes the result.


Итак, судя по выделенному:
(i1 ?? i2) -> A == int?, B == int?, A0 == int
Из B (как впрочем и из i2) у нас нет implicit conversion в A0
Судя по следующему, за выделенным пунктом, тип результата должен быть A. Но это не так. Почему?

Аналогичные проблемы и для остальных случаев. Особенно меня беспокоит случай №4, что мешало остаться нуллаблом?
Я что-то упустил или неправильно понимаю?
... << RSDN@Home 1.2.0 alpha rev. 0>>
Превратим окружающую нас среду в воскресенье.
 
Подождите ...
Wait...
Пока на собственное сообщение не было ответов, его можно удалить.