4 June 2007

Ternary Operator

by mo


I have come to 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.

Boolean 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 yields a false value and executes the false condition. The 2nd reason this works is because mO is not cool! Here is maybe 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 came across the ?? operator added in C# 2.0. 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.

csharp