Ternary operator in C#

Ternary operator C# example-Learn how to compare two values using ternary operator (? : ) and how to execute the statement with explanation and example programs.

When ever we want to compare 2 values, we can do with the if else statement as shown below.

if(a>b)
{
 Console.WriteLine("A is greater than B");

}
else
{
 Console.WriteLine("B is greater than A");  
}

In the same way whenever we want to compare 2 values, we can also do with a special decision making operator called ternary operator i.e (? : ) which is similar to if-else.

string output = A>B?"A is greater than B":"B is greater than A";

Syntax:

data_type Output_Variable=condition? statementnt1 : statement2;

Condition is the boolean expression.
statement1 is evaluated if condition is true and statement2 is evaluated if condition is false.

C# Ternary Operator Example

c# code

 /*---------------------------------------------
 * IF Else and Ternary operator example in C#
 */

    public class ToStringExample
    {

        public static void Main(String[] args) {
 
		int a = 5, b = 10;
		String result;
		
		/*---------------------------------------------
		 * Using IF then Else example
		 */
 
		if (a < b) {
			result = " a is less than b";
		} else {
			result = " a is greater than b";
		}
		
		Console.WriteLine("result using if else condition : " + result);
		
		/*---------------------------------------------
		 * Using Ternary operator example
		 */
 
		result = a < b ? " a is less than b" : " a is greater than b";

        Console.WriteLine("result using ternary operator  : " + result);
	}

    }

Output:
result using if else condition : a is less than b
result using ternary operator : a is less than b

NOTE:
Ternary operator makes the code shorter. There is no performance difference between Ternary operator and if – else.
use ternary operator only if the code is one liner and no change in the code in future. other wise use if -else.

Related Posts