Me Myself & C#

Manoj Garg’s Tech Bytes – What I learned Today

Null-coalescing operator in C#

Posted by Manoj Garg on May 12, 2009

While surfing around I can across a term called “null-coalescing operator”. After searching about it, I came to know that C# has an operator ?? . well I didn’t new about it before so thought of writing about it.

MSDN says

The ?? operator is called the null-coalescing operator and is used to define a default value for a nullable value types as well as reference types. It returns the left-hand operand if it is not null; otherwise it returns the right operand.

Example:

int? x = null;
string str = "Hello World !!"; 

int y = x ?? -99; // Here Y will be -99 since X is null
string newStr = str ?? "Default Hello World !!"; // here newStr will be "Hello World !!"

PS: This operator reminded me of similar functions available in SQL Server like ISNULL, COALESCE

Advertisements

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 )

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

 
%d bloggers like this: