TheChaseMan's Frenetic SoapBox

Always looking for better ways to do things...

Nullable Types - C# v2.0

From the C# 2.0 Spec - very cool stuff!



Nullable types are constructed using the ? type modifier. For example, int? is the nullable form of the predefined type int. A nullable type’s underlying type must be a value type.


int? x = 123;
int? y = null;

if (x.HasValue) Console.WriteLine(x.Value);
if (y.HasValue) Console.WriteLine(y.Value);

 

Some examples of nullable conversions are shown in the following.


int i = 123;
int? x = i; // int --> int?
double? y = x; // int? --> double?
int? z = (int?)y; // double? --> int?
int j = (int)z; // int? --> int


A new null coalescing operator, ??, is provided. The result of a ?? b is a if a is non-null; otherwise, the result is b. Intuitively, b supplies the value to use when a is null.

Console.WriteLine(s ?? "Unspecified");

...outputs the value of s, or outputs Unspecified if s is null.
 


Digg!

posted on Tuesday, May 25, 2004 9:58 AM

Feedback

No comments posted yet.