logo search
CSharp_Prog_Guide

Примеры допускающих значение null типов

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

int? i = 10;

double? d1 = 3.14;

bool? flag = null;

char? letter = 'a';

int?[] arr = new int?[10];

The Members of Nullable Types

Each instance of a nullable type has two public read-only properties:

HasValue is of type bool. It is set to true when the variable contains a non-null value.

Value is of the same type as the underlying type. If HasValue is true, Value contains a meaningful value. If HasValue is false, accessing Value will throw a InvalidOperationException.

In this example, the HasValue member is used to test whether the variable contains a value before it tries to display it.

int? x = 10;

if (x.HasValue)

{

System.Console.WriteLine(x.Value);

}

else

{

System.Console.WriteLine("Undefined");

}

Testing for a value can also be done as in the following example:

int? y = 10;

if (y != null)

{

System.Console.WriteLine(y.Value);

}

else

{

System.Console.WriteLine("Undefined");

}