Sunday, 19 January 2014

C# coalesce operator : Question Mark In C# and Double Question Mark

Leave a Comment
A not so common, but very useful operator is the double question mark operator (??). This can be very useful while working with null able types.
Lets say you have two nullable int:

int? numOne = null;
int? numTwo = 23;

Note : int? (data type with question mark used to declare variable with null able type)

Scenario: If numOne has a value, you want it, if not you want the value from numTwo, and if both are null you want the number ten (10).

Old solution:

if (numOne != null)
    return numOne;
if (numTwo != null)
    return numTwo;
return 10;

Or another solution with a single question mark:

return (numOne != null ? numOne : (numTwo != null ? numTwo : 10));

But with the double question mark operator we can do this:

return ((numOne ?? numTwo) ?? 10);

Output : return numOne if have value, else return numTwo else return 10;
As you can see, the double question mark operator returns the first value that is not null.

By
NOTE : – If You have Found this post Helpful, I will appreciate if you can Share it on Facebook, Twitter and Other Social Media Sites. Thanks =)

0 comments:

Post a Comment

Subscribe to our newsletter to get the latest updates to your inbox.

Your email address is safe with us!




Founder of developersnote.com, love programming and help others people. Work as Software Developer. Graduated from UiTM and continue study in Software Engineering at UTMSpace. Follow him on Twitter , or Facebook or .



Powered by Blogger.