Wednesday, June 24, 2009

C# coalesce, double question-mark (??) operator

I have been coding in C# for years now but never knew this - the coalesce like operator in C#.


If I had to check a value with null before using it, I use the well known ternary operator (? :). But C# made our lives easier by introducing ?? operator for this task. For example, if you have a variable isParent and need to check for null, you can do:
isParent != null ? isParent : default_value;

Now, with the new ?? operator, we can write the same as:
isParent ?? default_value;

With the above expression, isParent will be used only if it is not null otherwise, default_value will be used. Its clean, isn't it? This might be a simple operator but it sure saves us from introducing few errors specially when we have some checks with nested ternary operators.

PS: This was introduced with nullable types in C#, and is available from .Net 2.0.

No comments: