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.
- Check if it is equal to null, as in == null
- Check the HasValue property.
If (null)will generate an exception. This code won't compile:
bool? bvar = null;However, all nullable variables have a Value property so
if (bvar) //Compiler error
DoSomething();
bool? bvar = null;Will compile but generates an exception. You need to guard it by checking HasValue first as in
if (bvar.Value) //Compiles but excepts
DoSomething();
bool? bvar = null;We'll return to nullable types in future lessons on databases.
if (bvar.HasValue && bvar.Value) // Ok but won't DoSomething
DoSomething() ;
On the next Page : Using Char Types

