This is a mirror of official site: http://jasper-net.blogspot.com/

Understanding C#: Nullable Types

| Sunday, November 14, 2010
Every C# developer knows how to work with value types like int, double, boolean, char, and DateTime. They're really useful, but they have one flaw: they can't be set to null. Luckily, C# and .NET give you a very useful tool to for this: nullable types. You can use a nullable type any place that you need a variable that can either have a value or be null. This seems like a simple thing, but it turns out to be a highly flexible tool that can help make your programs more robust.

In this tutorial, which I've adapted from my book, Head First C#, I'll show you the basics of nullable types, and give you a quick example of a program that uses them to handle unpredictable user input.

Use nullable types when you need nonexistent values

If you're a Head First C# reader, take a minute and flip back to the contact cards you converted to a database way back in the Contacts project in Chapter 1. (If you're not a Head First C# reader, that chapter is a tutorial that walks you through creating a simple database-driven application for managing contacts. You download the first three full chapters—here's a link to the free Head First C# eBook PDF download.) In the Contacts project project, you set up your table to allow nulls for each of its columns. That way, if someone left out a value or wrote something illegible on their contact card, the database could use null to represent that it doesn't have a value.

Did it seem odd that even the Client column was set to allow nulls? Someone's either a client or not, right? But there was no guarantee that every card has the Client blank filled in, and the database needed a way to represent that we might not know if someone's a client or not.

Now, in a database you could just use null. But value types like ints and Booleans can't be set to null. If you added these statements to your program:

 bool myBool = null;
 DateTime myDate = null;

you'd get a compiler error.

Read more: O'Relly community

Posted via email from .NET Info

0 comments: