Nullable Values
Most value types do not provide a means to indicate that they contain an undefined value. Unlike reference types, which are null by default and can be set to a null reference in code, uninitialised value types contain a default value that lies within their normal range. One way to work around the problem is to designate a particular value to indicate that a variable is undefined. For example, if you have a variable that should only contain positive integers, you may decide that -1 indicates that the user has yet to provide a value. This is problematic when all possible values could are valid. For example, you may wish to have a Boolean with three states: true, false and undefined. This is often the case when working will nullable information from databases.The Nullable
NB: Nullable numeric types have been discussed as part of the C# Fundamentals Tutorial. Here they were seen using the ? syntax, where int? is equivalent to Nullable
Using Nullable
There are several ways in which a nullable type can be instantiated. The first way that we will examine is using a constructor. The NullableIn the sample code below, two nullable integers are instantiated. The first will contain the value 10 and the second will be null.
Nullablevalue = new Nullable (10); Nullable nullValue = new Nullable ();
Nullablevalue = 10; Nullable nullValue = null;
HasValue and Value Properties
The NullableTry adding the sample code below after the two previous declarations to see the property in action:
bool hasValue; hasValue = value.HasValue; // true hasValue = nullValue.HasValue; // false
int nonNullable; nonNullable = value.Value; // 10 nonNullable = nullValue.Value; // Exception
GetValueOrDefault Method
The GetValueOrDefault method provides a second means for reading the value from a nullable type. When used with no parameters, the method returns the wrapped value if one is present. If the value is null, the method returns the default value for the wrapped type. In the case of our wrapped integers, the default value is zero:nonNullable = value.GetValueOrDefault(); // 10 nonNullable = nullValue.GetValueOrDefault(); // 0
nonNullable = value.GetValueOrDefault(99); // 10 nonNullable = nullValue.GetValueOrDefault(99); // 99
Casting
We have already seen that a non-nullable value can be implicitly cast to a nullable version of the same type. This was seen in the second code sample with the line:Nullable value = 10;
There is no support for implicit casting of a nullable value to its non-nullable counterpart. However, the NullablenonNullable = (int)value;
No comments:
Post a Comment