Free mag vol1 | Page 224

CHAPTER 4  CORE C# PROGRAMMING CONSTRUCTS, PART II else Console.WriteLine("Value of 'i' is undefined."); } // Get bool from "database". bool? b = dr.GetBoolFromDatabase(); if (b != null) Console.WriteLine("Value of 'b' is: {0}", b.Value); else Console.WriteLine("Value of 'b' is undefined."); Console.ReadLine(); The ?? Operator The final aspect to be aware of with nullable types is that they can make use of the C# ?? operator. This operator allows you to assign a value to a nullable type if the retrieved value is in fact null. For this example, assume you want to assign a local nullable integer to 100 if the value returned from GetIntFromDatabase() is null (of course, this method is programmed to always return null, but I am sure you get the general idea): static void Main(string[] args) { Console.WriteLine("***** Fun with Nullable Data *****\n"); DatabaseReader dr = new DatabaseReader(); ... // If the value from GetIntFromDatabase() is null, // assign local variable to 100. int myData = dr.GetIntFromDatabase() ?? 100; Console.WriteLine("Value of myData: {0}", myData); Console.ReadLine(); } The benefit of using the ?? operator is that it provides a more compact version of a traditional if/else condition. However, if you want, you could have authored the following functionally equivalent code to ensure that if a value comes back as null, it will indeed be set to the value 100: // Long-hand notation not using ?? syntax. int? moreData = dr.GetIntFromDatabase(); if (!moreData.HasValue) moreData = 100; Console.WriteLine("Value of moreData: {0}", moreData); With this, our initial investigation of the C# programming language is complete! In Chapter 5, you will begin to dig into the details of object-oriented development.  Source Code The NullableTypes application is located under the Chapter 4 subdirectory. 159