Overview of C# nullable types
Asp.net 2.0 introduced nullable types that allow you to determine whether a variable has been assigned a value or not and not cause an exception if the variable is null. A nullable type simply allows a variable to be null in addition to its normal range of values. A nullable string for example, can be any text representation as well as null. Likewise a nullable boolean value can be true, false or null.
A nullable type can be represented by the ? operator or by the Nullable <T> syntax. The following two statements are identical and define a nullable integer:
Nullable<int> myNullableInt; int? myNullableInt;
Nullable types are most useful when working with database queries that may return null. The following example shows a class with database operations performed against it where some fields may be null.
We’ll start off by defining the class without any nullable operators:
public class Event
{
public int EventID { get; set; }
public string EventName { get; set; }
public DateTime EventDate { get; set; }
}
In this case we’re going to allow the EventDate field to be null in the database. Without setting a nullable type, you’ll receive a number of errors when retrieving and updating this value.
Firstly, when retrieving from a database:
SqlDataReader reader = cmd.ExecuteReader();
while (reader.Read())
{
myEvent = new Event();
myEvent.EventID = (int)reader["RegistryID"];
myEvent.EventName = (string)reader["EventName"];
myEvent.EventDate = (DateTime)reader["EventDate"];
}
You’ll get the following error:
Specified cast is not valid.
The way to resolve this is to modify the class to make the EventDate property a nullable type:
public DateTime? EventDate { get; set; }
The database code changes the same way:
myEvent.EventDate = reader["EventDate"] as DateTime?;
Finally, there are a few things you need to do differently when displaying, and updating your data.
When displaying the value in a textbox or label, use TryParse to see if this is a valid date – if not then display empty text. (For more on TryParse, see James Michael Hare’s excellent post here):
DateTime date; if (DateTime.TryParse(myEvent.EventDate.ToString(), out date)) EventDate.Text = date.ToShortDateString(); else EventDate.Text = String.Empty;
After editing then use the ?? operator to save a DBNull value if the EventDate is null:
cmd.Parameters.AddWithValue("@EventDate",
EventtoUpdate.EventDate ?? (object)DBNull.Value);
The ?? operator simply says use the value of EventtoUpdate.EventDate if it is not null, otherwise save the value as DBNull.Value (the database representation of null)










