Use nullable types to assign null values to value types and avoid run-time exceptions in your applications.
by Joydip Kanjilal
October 12, 2007
orking with value types was sometimes awkward in .NET 1.x, because they could cause serious problems in applications that retrieved data from database tables containing columns that can have null values—those that may or may not hold data. C# 2.0 presents a new concept called "nullable types" that lets you initialize value types to null values. This article discusses how you can apply the new nullable types feature to solve issues that result from having null values in database columns.
Why Nullable Types?
Value types are "primitive" data types such as numbers. The .NET Framework stores value types in the stack and implicitly initializes them to their default values—even if you do not explicitly initialize them when they are defined. For example, an int gets initialized to 0, a bool to false, and so on. Unfortunately, most value types are unable to represent a null value, which presents a problem when you're working with data-centric applications where null values are possible, because you have to select some other value to represent null. But whatever value you choose to represent null is no longer available as a valid data value, which restricts the range of permissible values. In other words, if you elect to use -1 to represent null, you've removed -1 as a valid value from the range of numbers that the value type can support. In addition, you must check to ensure that the chosen "null-representation" values are ignored in other parts of the application—and you must make sure not to display the null-representation values directly to end users, who may not understand that the value represents null.
It's quick, easy and you get access to all the articles on DevX.
This registration/login is to allow you to read articles on devx.com. Already a member?
To become a member of DevX.com create your Member Profile by completing the form below. Membership is free!