Current .Net Version: 2.0.50727
Home
Articles
C# & .Net Framework Reference
Practice C# Online
XML Web Services
RSS Feeds
Code Snippets
T-SQL Scripts
Videos
Valuable Links
Contact Us
Mike's C#, VS.NET and SQL Blog




ROR XML Info.
What's New in C# 2.0 - Nullable Types
Author: Michael G.     Last Updated:9/29/2005 8:03:35 PM
Category(ies): C# 2.0, .Net Framework 2.0
Description: Learn all about the new C# 2.0 Framework feature: Nullable Types.
  Add & View Comments About this Article

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? (where T is the type (class, struct, etc.).

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.");

Comments Click Here to Add your Comment
 
COPYRIGHT/DISCLAIMER | CONTACT US