Nullable Modifier


As I pointed out earlier, value types cannot be assigned null because, by definition, they can't contain references, including references to nothing. However, this presents a problem in the real world, where values are missing. When specifying a count, for example, what do you enter if the count is unknown? One possible solution is to designate a "magic" value, such as 0 or int.Max, but these are valid integers. Rather, it is desirable to assign null to the value type because this is not a valid integer.

To declare variables that can store null you use the nullable modifier, ?. This C# 2.0 feature appears in Listing 2.17.

Listing 2.17. Using the Nullable Modifier

static void Main() {   int? count = null;   do   {       // ...   }   while(count == null); }

Assigning null to value types is especially attractive in database programming. Frequently value type columns in database tables allow nulls. Retrieving such columns and assigning them to corresponding fields within C# code is problematic, unless the fields can contain null as well. Fortunately, the nullable modifier is designed to handle such a scenario specifically.




Essential C# 2.0
Essential C# 2.0
ISBN: 0321150775
EAN: 2147483647
Year: 2007
Pages: 185

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net