Step by Step

Monday, May 9, 2011

Understanding the Problem with Value Types and Null Values


Working with value types and data can sometimes be challenging because a value type doesn't normally hold a null value. This lesson show you how to overcome this limitation with C# nullable types. Here's what you'll learn.

* Understand the problem that nullable types solve
* See how to declare a nullable type
* Learn how to use nullable types

 Structs, the default value of a struct (value type) is some form of 0. This is another difference between reference types and value types. The default value of a reference type is null. If you're just writing C# code and managing your own data source, such as a file that holds data for your application, the default values for structs works fine.

In reality, most applications work with databases, which have their own type systems. The implications of working with database type systems is that you don't have a one-to-one mapping between C# and database types. One glaring difference is that database types can be set to null. A database has no knowledge of reference and value types, which are C# language (.NET Platform) concepts. This means that C# value type equivalents in the database, such as int, decimal, and DateTime, can be set to null.

Since a type in the database can be null, but your C# value type can't be null, you have to find some way to provide a translation in your C# code to account for null values. Effectively, the scheme you use will often be inconsistent from one program to another; something you often don't have a choice about. For example, what if you wanted to handle a null DateTime from SQL Server as the minimum DateTime value in C#. After that project, your next task would be to read data from a legacy Foxpro database, whose minimum DateTime value is different from SQL Server. Because of this lack of constency and potential confusion, C# 2.0 added nullable types, which are more elegant and natural for working with null data.

0 comments: