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 =

      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”]

Got something to add?

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s