The Conditional Operator (?:)

I don’t use this thing too much, so I often forget it when I need it.  In a nut shell it is a nice one line if statement.  You can view the MS page here.

The conditional operator (?:) returns one of two values depending on the value of a Boolean expression. Following is the syntax for the conditional operator.
The condition must evaluate to true or false. If condition is true, first_expression is evaluated and becomes the result. If condition is false, second_expression is evaluated and becomes the result. Only one of the two expressions is evaluated.

condition ? first_expression : second_expression;

Let me provide a realistic example.  Lets say you have a method to generate a random number from 1 – 4, and you want to see if the number is odd or even.

private int RandomNumber(int min, int max)
    Random random = new random();
    return random.Next(min, max);

private string NumberIs()
    string sNumberIs = (RandomNumber(1, 4) % 2 == 0) ? "Even" : "Odd";
    return sNumberIs;

About SheldonS

Web developer for over 15 years mainly with Microsoft technologies from classic ASP to .NET 4. Husband, father, and aspiring amateur photographer.

Posted on March 7, 2011, in Bits, C# and tagged . Bookmark the permalink. Leave a comment.

Leave a Reply

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

You are commenting using your 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

This site uses Akismet to reduce spam. Learn how your comment data is processed.

%d bloggers like this: