Information Technology Reference
In-Depth Information
You can use the two read-only properties explicitly as follows.
int? MyInt1 = 15;
Explicitly use the property.
if ( MyInt1.HasValue )
Console.WriteLine("{0}", MyInt1.Value );
Explicitly use the property.
A better method, however, is to use the shortcut forms, as shown in the following code.
To check whether a nullable type has a value, you can compare it to null .
￿
￿
Like any variable, to retrieve its value, you can just use its name.
Compare to null.
if (MyInt1 != null)
Console.WriteLine("{0}", MyInt1);
Use variable name.
Both sets of code produce the following output:
15
Reading a variable of a nullable type returns its value. You must, however, make sure that
the variable is not null . Attempting to read the value of a null variable produces an exception.
You can easily convert between a nullable type and its corresponding non-nullable type.
￿There is an implicit conversion between a non-nullable type and its nullable version.
That is, no cast is needed.
￿There is an explicit conversion between a nullable type and its non-nullable version.
For example, the following lines show conversion in both directions. In the first line, a literal
of type int is implicitly converted to a value of type int? and is used to initialize the variable of the
nullable type. In the second line, the variable is explicitly converted to its non-nullable version.
int? MyInt1 = 15; // Implicitly convert int to int?
int RegInt = (int) MyInt1; // Explicitly convert int? to int
Search WWH ::




Custom Search