Showing posts with label ?? Operator. Show all posts
Showing posts with label ?? Operator. Show all posts

Saturday, August 16, 2008

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

3 comments
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#
Read more...