logo
CSharp_Prog_Guide

Члены допускающих значение null типов

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

Свойство HasValue имеет тип bool. Это свойство имеет значение true, если переменная содержит определенное значение.

Свойство Value имеет тот же тип, что и лежащий в основе тип. Если свойство HasValue имеет значение true, то свойство Value содержит имеющее смысл значение. Если свойство HasValue имеет значение false, то доступ к свойству Value будет приводить к формированию ошибки InvalidOperationException.

В этом примере член HasValue используется для выполнения проверки, содержит ли переменная какое-либо значение, прежде чем пытаться его показать.

----

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

int? y = 10;

if (y != null)

{

System.Console.WriteLine(y.Value);

}

else

{

System.Console.WriteLine("Undefined");

}

Explicit Conversions

A nullable type can be cast to a regular type, either explicitly with a cast, or by using the Value property. For example:

int? n = null;

//int m1 = n; // Will not compile.

int m2 = (int)n; // Compiles, but will create an exception if x is null.

int m3 = n.Value; // Compiles, but will create an exception if x is null.

If a user-defined conversion is defined between two data types, the same conversion can also be used with the nullable versions of these data types.

Implicit Conversions

A variable of nullable type can be set to null with the null keyword, as shown in the following example:

int? n1 = null;

The conversion from an ordinary type to a nullable type, is implicit.

int? n2;

n2 = 10; // Implicit conversion.