C# – Ternary operator

One of C#’s most fascinating operators is the ?, which is C#’s conditional operator. The ? operator is often used to replace certain types of if-then-else constructions. The ? is called a ternary operator because it requires three operands.
It takes the general form

Exp1 ? Exp2 : Exp3;

where Exp1 is a bool expression, and Exp2 and Exp3 are expressions. The type of Exp2 and Exp3 must be the same (or, an implicit conversion between them must exist). Notice the use and placement of the colon.

The value of a ? expression is determined like this: Exp1 is evaluated. If it is true, then Exp2 is evaluated and becomes the value of the entire ? expression. If Exp1 is false, then Exp3 is evaluated, and its value becomes the value of the expression. Consider this example, which assigns absval the absolute value of val:absval = val < 0 ? -val : val; // get absolute value of val

Here, absval will be assigned the value of val if val is zero or greater. If val is negative, then absval will be assigned the negative of that value (which yields a positive value). Here is another example of the ? operator. This program divides two numbers, but will not allow a division by zero.

 // Prevent a division by zero using the ?. 
 using System; 
 class NoZeroDiv { 
 static void Main() {
 int result;   
 for(int i = -5; i < 6; i++) { 
 result = i != 0 ? 100 / i : 0; 
 if(i != 0)        
 Console.WriteLine("100 / " + i + " is " + result); 
 }  
 } 
 }
 The output from the program is shown here:
 100 / -5 is -20 
 100 / -4 is -25 
 100 / -3 is -33 
 100 / -2 is -50 
 100 / -1 is -100 
 100 / 1 is 100 
 100 / 2 is 50 
 100 / 3 is 33 
 100 / 4 is 25 
 100 / 5 is 20
  • Ternary operator: boolean expression ? first statement : second statement;
  • Ternary operator returns a value, it does not execute it.
  • It can be used to replace a short if-else statement.
  • A nested ternary operator is allowed. It will be evaluted from right to left.
0 0 votes
Article Rating

Do you want to hire us for your Project Work? Then Contact US.
Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x