Saturday, August 16, 2008

The Coalesce Operator (The ?? Operator in C#)e


The Conventional Way

if (obj1 != null)
{
objOut = obj1;
}
else
{
objOut = obj2;
}

The Ternary Operator
objOut = (obj1 != null) ? obj1 : obj2;


The Coalesce Operator Way
objOut = obj1 ?? obj2;


The Extended Coalesce Operator

The Conventional Way
if (obj1 != null)
{
return obj1;
}
else if (obj2 != null)
{
return obj2;
}
else if (obj3 != null)
{
return obj3;
}
else
{
return null;
}

The Coalesce Operator Way
return obj1 ?? obj2 ?? obj3;


As a useful replacement to the Ternary Operator

The Ternary Operator Way
obj = (obj != null)? obj : objNew;

The Coalesce Operator Way
obj = obj ?? objNew;


Then why is not used more? I think cos its got a tough name.[:)]
How do you pronounce it?

I LOVE C#

Related Posts :



3 comments on "The Coalesce Operator (The ?? Operator in C#)e"

Add your comment. Please don't spam!
Subscribe in a Reader
Mav-eric on September 5, 2008 at 1:45 PM said...

is it "Coalsce Operator" or "Coalesce Operator". anyways its an added advanage when compared to Ternary operator

Naveen on October 21, 2009 at 2:46 PM said...

thanx Mav-eric.
I have dealt with the typo

Binil on December 30, 2010 at 5:12 PM said...

great post...

Post a Comment