C / C++ / C#

  1. Home
  2. Computing & Technology
  3. C / C++ / C#

C# Tutorial - Learn the Fundamentals of Programming

By David Bolton, About.com

7 of 8

Working with Nullable Types

Nullable Types

If you've ever converted a spreadsheet into a database you'll probably have experienced the null value. This is a value that means No Value present, much like a blank cell in a spreadsheet. Null values can sometimes give applications grief. If you're expecting an int value and you get a null, how do you deal with it? Does it default to zero or set the int variable to a 'Magic Value' that means no value present?

C# has added support for this by letting you make many types nullable. By adding a ? after the type name, ugly though it looks, it makes the variable nullable so that it can now hold a null value. Only value types can be made nullable- we'll look at value and reference types in the next lesson. Reference Types (eg strings and objects) are already nullable.

int? ivar = null;
This gives you tri-state logic with bools so that bool? variables can take null, false or true values. You can test for a null value in two ways.
  1. Check if it is equal to null, as in == null
  2. Check the HasValue property.
Only variables of nullable types have the HasValue property. Note Some care must be taken when using nullable bool variables, particularly in expressions.
If (null)
will generate an exception. This code won't compile:
bool? bvar = null;
if (bvar) //Compiler error
   DoSomething();
However, all nullable variables have a Value property so
bool? bvar = null;
if (bvar.Value) //Compiles but excepts
   DoSomething();
Will compile but generates an exception. You need to guard it by checking HasValue first as in
bool? bvar = null;
if (bvar.HasValue && bvar.Value) // Ok but won't DoSomething
   DoSomething() ;
We'll return to nullable types in future lessons on databases.

On the next Page : Using Char Types

Explore C / C++ / C#

About.com Special Features

C / C++ / C#

  1. Home
  2. Computing & Technology
  3. C / C++ / C#
  4. C# / C Sharp
  5. Learn C Sharp
  6. Working with Nullable Types

©2009 About.com, a part of The New York Times Company.

All rights reserved.