Ternary operator

The .NET framework has a cool feature called the Ternary Operator.  It’s basically a shortcut for  an if/then/else statement.

Here’s the format:
condition ? first_expression : second_expression;

The condition must be something that evaluates to true or false.  The first expression is what get’s returned if the condition is true.  Obviously the second expression gets returned if the condition is false.

I make use of then when I’m pulling data from a source and loading an object (ie, handle null from the source).

So here we have a normal check for null.  If it is null then set the property to String.Empty otherwise set to the value.

if (FirstName == null)
{

emp.FirstName =

String.Empty;}
else
{
      emp.FirstName = FirstName;
}

Here is the same statement using the new format.

emp.FirstName  = (FirstName == null) ? String.Empty : emp.FirstName = FirstName;

Much more compact code.

Remember you need both the ? and :

Don’t forget those.

[tweetmeme only_single=”false”]