C# Ternary Operator

C# includes a decision-making operator ?: which is called the conditional operator or ternary operator. It is the short form of the if else conditions.

Syntax:
condition ? statement 1 : statement 2


The ternary operator starts with a boolean condition. If this condition evaluates to true then it will execute the first statement after ?, otherwise the second statement after : will be executed.

The following example demonstrates the ternary operator.

Example: Ternary operator
int x = 20, y = 10;

var result = x > y ? "x is greater than y" : "x is less than y";

Console.WriteLine(result);

output: 

x is greater than y

Above, a conditional expression x > y returns true, so the first statement after ? will be execute.

Comments

Popular posts from this blog

C# | Association, Aggregation and Composition

Throw vs Throw ex in C#

C# Extension Method