I have become a big fan of the ternary operator… It’s quite useful for replacing simple if-else statements.
Ternary operator template:
( true/false expression to evaluate ) ? (true evaluation) : (false evaluation) ;
E.g.
bool IsMoCool = false;
string s = (IsMoCool) ? "Mo is cool" : "Mo is not cool";
Console.WriteLine(s);
Can you predict the result? This should print “Mo is not cool” to the console window. This happens for 2 reasons, the first is the “IsMoCool” value is initialized as false. So when the statement ( IsMoCool ) evaluated it yeilds a false value and executes the false condition. The 2nd reason this works is because mO is not cool!
Here is a better usage of the ternary operator…
Let’s say I have the following code…
public class TernaryDemo
{
private object _myObject;
public object MyObject
{
get { if( null == _myObject ) { _myObject = new object(); } return _myObject; }
}
}
This could be re-written as….
public class TernaryDemo
{
private object _myObject;
public object MyObject
{
// if _myObject hasn't been constructed yet then create an instance,
// otherwise return the constructed instance.
get { return ( null == _myObject ) ? _myObject = new object() : _myObject; }
}
}
Recently I was reading an article from an MSDN blog… (I’m sorry I didn’t save the link… I will have to look it up later.) And I came across the ?? operator added in C# 2.0. Whoa!
Here’s how (I think) it works…
private string _s;
public void MyMethod()
{
string s = ( null == _s) ? "Some Clever Text Here" : _s;
}
The above code can be re-written using ?? like this…
private string _s;
public void MyMethod()
{
string s = _s ?? "Some Clever Text Here";
}
The ?? operator implicitly does the same operation as the ternary operator but looks much cleaner. I’m not sure if I’m a fan yet, but I’d love to hear what you think!