Joe Wood's Blog

Technology

<August 2008>
SuMoTuWeThFrSa
272829303112
3456789
10111213141516
17181920212223
24252627282930
31123456


Navigation

Subscriptions



Thursday, June 16, 2005 - Posts

VS 2005 Cool new feature #1 - The '??' Operator

I thought I'd blog about some of the less talked about new features in VS 2005.

This one is in the C# language - I discovered it at the C# SDR during one of the demos.  It can be best summarized as follows:

Old method:

object result = GetResult(); // return some object, that can be null
Console.WriteLine( result==null ? “NULL” : result );  // write 'NULL' if the returned value is NULL, otherwise just write ToString()

New method:

object result = GetResult(); // return some object, that can be null
Console.WriteLine( result ?? “NULL” );  // syntax is abbreviated, result is used unless the value is null - otherwise the value after '??' is used.

This operator becomes very useful when using nullable types:

int? result = GetResult();
int total = 300;
total = total + result; // ! compiler error - cannot add a nullable int to a non-nullable int
total = total + result ?? 0; // Correct usage - result defaults to 0 if null

 

posted Thursday, June 16, 2005 9:57 AM by joewood with 1 Comments




Powered by Dot Net Junkies, by Telligent Systems