Monday 28 May, 2007

C#'s ?? Operator

Here is something new and interesting: A new operator in C# "??" Operator

This operator is responsible for defining a default value assignment if the value to be assigned is null. Let's say you want to assign value of y to x only if y is not null, else you want to assign z.

So, you may write your code something like this:

if (y != null)
x = y;
else
x = z;

You can also use Ternary operator for this:

x = ((y != null) ? y : z)

So, for this long statement and frequent null checks, here is the new C# operator: ??

x = y ?? z

Here it checks if y is not null, then assigns y, else assigns z. So, syntax goes like this:

x = {value to be checked for null} ?? {default value}

Very very interesting :) And ya, it was Ankit who mentioned it first, so we had a little chat over it (I am mentioning his name, otherwise he is going to kill me :))

For more information, visit: http://msdn2.microsoft.com/en-us/library/ms173224(vs.80).aspx

- Mohit

No comments: