Tuesday, January 20, 2015

Coalescing operator ?? in C#

?? operator in C# is a binary operator. It is also called as null coalescing operator, which returns the left hand operand if it has any value, else, returns the right hand operator. Confused, let's see an example for this.
Suppose we have a property UserId of type int and nullable in nature. While using this property, if it has any value i.e. Not Null, then use that value, else, use some other value. So first thing that comes to mind is use the if-else, something like below:

Null coalescing operator provides a very shorthand syntax for this, which changes the code to:

Easy and concise to use. Happy coding...!!!

No comments:

Post a Comment