C# .Net Fun Current .Net Version: 1.1.4322

C# Reference
XML Web Services
Contact Us
Feeds
What's New in C# 2.0 - Nullable Types
Author:Michael G.
Category(ies):.Net Framework 2.0, C# 2.0
Description:Learn all about the new C# 2.0 Framework feature: Nullable Types.

Tested with Microsoft Visual C# 2005 Beta 1, .Net 2.0.40607.42

Did any of you programmers ever think you'd see the day you could assign null values to value types? Well, you can now!

You can now assign the null value to value types by defining nullable types. You do this by adding a question mark to the immediate right of the type name when defining a variable. Nullable types derive from the generic type System.Nullable<T>. Instead of defining types from this generic class, you can simply just use <T>?.

Two properties make nullable types quite useful: HasValue and Value. HasValue evaluates to true if the type is not null, otherwise it's false. Value will return the underlying value, whether it's null or not.
// both of these refer to the same nullable interger type: int? myInt1 = null; Nullable<int> myInt2 = null; if (myInt1 == null) Console.WriteLine("myInt1 is null."); if (myInt2 == null) Console.WriteLine("myInt2 is null."); // Or, we can check for a value this way: myInt1 = 1; if (myInt1.HasValue) Console.WriteLine("myInt1 has a value = {0}", myInt1.Value); else Console.WriteLine("myInt1 is null.");
 
COPYRIGHT/DISCLAIMER | CONTACT US