Information Technology Reference
In-Depth Information
For example, the following code uses the previously declared struct, and creates variables
of both the struct and the corresponding nullable type. In the third and fourth lines of code, the
values of the struct's variables are read directly. In the fifth and sixth lines, they must be read
from the value returned by the nullable's Value property.
MyStruct MSStruct = new MyStruct(6, 11); // Variable of struct
MyStruct? MSNull = new MyStruct(5, 10); // Variable of nullable type
Struct access
Console.WriteLine("MSStruct.x: {0}", MSStruct.x);
Console.WriteLine("MSStruct.y: {0}", MSStruct.y);
Console.WriteLine("MSNull.x: {0}", MSNull.Value.x);
Console.WriteLine("MSNull.y: {0}", MSNull.Value.y );
Nullable type access
Nullable<T>
Nullable types are implemented by using a .NET type called System.Nullable<T> , which uses
the C# generics feature.
The question mark syntax of C# nullable types is just shortcut syntax for creating a variable
of type Nullable<T> , where T is the underlying type. Nullable<T> takes the underlying type and
embeds it in a structure, and provides the structure with the properties, methods, and con-
structors of the nullable type.
You can use either the generics syntax of Nullable<T> or the C# shortcut syntax. The short-
cut syntax is easier to write and to understand, and is less prone to errors.
The following code uses the Nullable<T> syntax with struct MyStruct , declared in the pre-
ceding example, to create a variable called MSNull of type Nullable<MyStruct> .
Nullable<MyStruct> MSNull = new Nullable<MyStruct>();
The following code uses the question mark syntax but is semantically equivalent to the
Nullable<T> syntax.
MyStruct? MSNull = new MyStruct();
Search WWH ::




Custom Search