Behind the Scenes Look at C#: Operators - The Ternary Operator
(Page 7 of 8 )
There's only one ternary operator in C#, the (?:) ternary operator. It has three arguments. This operator is very useful in writing elegant C# code because its first argument takes a Boolean expression, and if it's evaluated to true, the second argument executes; if it's evaluated to false, the third argument executes. Consider the following if statement:
static void Main(string[] args)
{
int x = 5;
if(x == 5)
{
Console.WriteLine("x equal to 5");
}
else
{
Console.WriteLine("x not equal to 5");
}
}
This code prints to the console "x equal to 5" but we can use the ternary operator to write more concise code, as follows:
int x = 5;
Console.WriteLine(x == 5? "x equal to 5" : "x not equal to 5");
You will get the same result to the console window and as you can see, only one line of code is needed.
Next: Operator Precedence >>
More C# Articles
More By Michael Youssef