Saturday, January 12, 2013

The ??(double question marks) Operator in C#.NET

My previous post will help you to understand the nullable types in .NET. The final aspect of nullable types to be aware of 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 wish 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);

No comments:
Write comments
Recommended Posts × +