Sep 4, 2007

?? Operator.. What is it good for?

Hi, Other day I was poking around C# 2.0 documentation and noted a different operator I had never seen before, ?? so I thought with myself: what is it good for? Well, after reading the documentation (remember, RTFM :) I couldn't believe I didn't known this before! The ?? operator is a binary operator that checks the left operand against null. If it is null, the expression result is the right operand value otherwise (left operand is not null) it will be the left operand value. See a sample:
string name = null;
Console.WriteLine("Value: {0}", name ?? "(null)"); // Writes: Value: (null)

name = "Adriano";
Console.WriteLine("Value: {0}", name ?? "(null)"); // Writes: Value: Adriano

Also, it is useful when used in conjunction to nullable value types.
int? i = null;
Console.WriteLine("Value: {0}", i ?? -1); // Writes: Value: (null)

i = 20;
Console.WriteLine("Value: {0}", i ?? -1); // Writes: Value: 20
PS: I've just started to play with
C# 3.0 (Visual Studio 2008 beta 2) and it seams to be a very strong language. PS2: Finally I managed to get SyntaxHighlighter to work with blogger (thanks to this post) As soon as I got more information I'll post my impressions here :) See you soon!

No comments: