Wednesday, September 30, 2009

Double question mark operator in C#

C# has a very neat coalesce operator (??). Here's a quick explanation.

(The following was taken from here)

For two nullable variables, a and b,

int? a = null;
int? b = 5;

If a is not null, return a.
If a is null, then return b only if b is not null.
If b is also null, then I want to return 10;

This logic is written as follows.

if(a != null)
return a;
if(b != null)
return b;
return 10;

Or it can be written as follows.

return (a != null ? a : (b != null ? b : 10));

Or it can also be written as follows.

return ((a ?? b) ?? 10);

No comments: