Iterators and Nullable Types - Nullable Types
(Page 2 of 4 )
Null Basics
Reference types can represent a nonexistent value with a null reference. Value types, however, cannot ordinarily represent null values. For example:
string s = null; // OK, Reference Type
int i = null; // Compile Error, Value Type cannot be null
To represent null in a value type, you must use a special construct called a nullable type. A nullable type is denoted with a value type followed by the? symbol:
int? i = null; // OK, Nullable Type
Console.WriteLine (i == null); // True
Nullable<T> struct
T? translates into System.Nullable<T>. Nullable<T> is a lightweight immutable structure, having only two fields, to represent Value and HasValue. The essence ofSystem.Nullable<T>is very simple:
public struct Nullable<T> where T : struct
{
public T Value {get;}
public bool HasValue {get;}
public T GetValueOrDefault();
public T GetValueOrDefault(T defaultValue);
...
}
The code:
int? i = null;
Console.WriteLine (i == null); // true
translates to:
Nullable<int>i = new Nullable<int>();
Console.WriteLine (! i.HasValue); // true
Attempting to retrieveValuewhenHasValueis false throws anInvalidOperationException.GetValueOrDefault()returnsValue ifHasValueis true; otherwise, it returnsnewT()or a specified custom default value.
The default value ofT?isnull.
Implicit and explicit nullable conversions
The conversion from T to T? is implicit, and from T? to T is explicit. For example:
int? x = 5; // implicit
int y = (int)x; // explicit
The explicit cast is directly equivalent to calling the nullable object’sValueproperty. Hence, anInvalidOperationExceptionis thrown ifHasValueis false.
Boxing and unboxing nullable values
When T? is boxed, the boxed value on the heap contains T, not T?. This optimization is possible because a boxed value is a reference type that can already express null.
Next: Lifted Operators >>
More C# Articles
More By O'Reilly Media
|
This article is excerpted from chapter four of C# 3.0 in a Nutshell, Third Edition, A Desktop Quick Reference, written by Joseph Albahari and Ben Albahari (O'Reilly; ISBN: 0596527578). Check it out today at your favorite bookstore. Buy this book now.
|
|