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 in C#

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

Null Coalescing operator in C#

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

Advertisements

About Jasminder

.Net developer and blogger by profession, keen to learn new technologies, love nature, music and cricket.
This entry was posted in C#, Interview Questions and tagged . Bookmark the permalink.

I have a suggestion..

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 )

Twitter picture

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

Facebook photo

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

Google+ photo

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

Connecting to %s