In c#, Ternary Operator (?:) is a decision-making operator, and it is a substitute for the if…else statement in c# programming language.
Using Ternary Operator, we can replace multiple lines of if…else statement code into a single line in c# programming language.
The Ternary operator will help you execute the statements based on the defined conditions using the decision-making operator (?:).
In c#, the Ternary Operator will always work with 3 operands. Following is the syntax of defining a Ternary Operator in c# programming language.
If you observe the above Ternary Operator syntax, the conditional operator (?:) will return only one value from the defined expressions, either first_expression or second_expression based on the value of a condition.
In c#, the Ternary Operator (?:) will work as follow.
As said earlier, the Ternary Operator (?:) is a substitute for the if…else statement in c# programming language. For example, we can replace the following if…else statement with Ternary Operator (?:) like as shown following.
If you observe the above example, we simplified the if…else condition by replacing multiple lines of the if…else condition code with Ternary Operator (?:) in c# programming language.
Now, we will see the complete example of a Ternary operator (?:) in c# programming language.
Following is the example of using a Ternary Operator (?:) in c# programming language.
If you observe the above code, we used a Ternary Operator (?:) to evaluate an expression (x > y) to show the result based on our requirements.
When you execute the above c# program, you will get the result below.
This is how we can use Ternary Operator (?:) as a substitute for if…else statement in c# programming language.
In c#, we can create a Nested Ternary Operator by including multiple conditional expressions as a second or third part of expressions in the ternary operator. These nested ternary operators will help us replace if…else if statements in c# programming language.
Following is the example of replacing if…else if statement with a nested ternary operator in c# programming language.
If you observe the above code, we are able to replace multiple lines of if…else if code with a single line of the nested ternary operator based on our requirements.
In c#, the conditional operator is a right-associative so the expression a ? b : c ? d : e; evaluated as a ? b : (c ? d : e), not as (a ? b : c) ? d : e.
Following is the example of defining a nested ternary operator in the c# programming language.
When we execute the above c# program, we will get the result below.
This is how we can implement a nested ternary operator in c# programming language to replace if…else if statements based on our requirements.