C# – coalesce operator – double question mark (??)

I find it very strange after spending quite a reasonable time of my life programming using C#, I have just come across this operator which is very useful, easy to work with and handy to make your code look as clean as you could wish for. THE DOUBLE QUESTION MARK (??) OPERATOR known as coalesce operator. An operator which is very useful while working with nullable types.

Let say we have two nullable integers:

int? nullableOne = null;
int? nullableTwo = 20;

What if you have been asked to provide a non-null value and if both the values are null then return default as 30? Immediately the following two solutions come to your mind:

Conditional IF
if(nullableOne != null)
return nullableOne;
if(nullableTwo != null)
return nullableTwo;
return 30;

Ternary Operation
return (nullableOne != null ? nullableOne : (nullableTwo != null ? nullableTwo : 30) );

but with coalesce operator the expression could be:

return (nullableOne ?? nullableTwo ?? 30);

This expression will return the first value that is not null.

This entry was posted in .NET C#. Bookmark the permalink.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s