logo
CSharp_Prog_Guide

Неявные преобразования

Переменной допускающего значение null типа может быть присвоено значение null с помощью ключевого слова null, как показано в следующем примере:

int? n1 = null;

Преобразование из обычного типа в допускающий значение null тип является неявным.

int? n2;

n2 = 10; // Implicit conversion.

Operators

The predefined unary and binary operators and any user-defined operators that exist for value types may also be used by nullable types. These operators produce a null value if the operands are null; otherwise, the operator uses the contained value to calculate the result. For example:

int? a = 10;

int? b = null;

a++; // Increment by 1, now a is 11.

a = a * 10; // Multiply by 10, now a is 110.

a = a + b; // Add b, now a is null.

When performing comparisons with nullable types, if one of the nullable types is null, the comparison is always evaluated to be false. It is therefore important not to assume that because a comparison is false, the opposite case is true. For example:

int? num1 = 10;

int? num2 = null;

if (num1 >= num2)

{

System.Console.WriteLine("num1 is greater than or equal to num1");

}

else

{

// num1 is NOT less than num2

}

The conclusion in the else statement is not valid because num2 is null and therefore does not contain a value.

A comparison of two nullable types which are both null will be evaluated to true.