Search This Blog

Tuesday, January 29, 2013

?: Operator (Ternary) (C#)

C# > OperatorsTernary (?:)

Ternary (conditional) operator (?:) returns one of two values depending on the value of a Boolean expression.

The syntax for the ternary operator is

condition ? first_expression : second_expression;

Example:




namespace WindowsFormsApplication1
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }
        private string OddOrEven(int x)
        {
            return (x % 2 == 0) ? "Number is even" : "Number is odd";
        }
        private void Form1_Load(object sender, EventArgs e)
        {
            string s;
            s = OddOrEven(10); // Number is even
            s = OddOrEven(11); // Number is odd
        }
    }
}