In this blog, I am going to share with you about Ternary Operator in C#.
Why should we use Ternary Operator?
Suppose we are creating a program in which we have to compare two values and based on it, execute the statement. Whenever we got that, we have to compare two values. We can do this with if and else, as shown in below program.
- using System;
- namespace Tutpoint
- {
- class Program
- {
- public static void Compare(int a, int b)
- {
- if (a > b)
- {
- Console.WriteLine("A is greater than B");
- }
- else
- {
- Console.WriteLine("B is greater than A");
- }
- }
- static void Main(string[] args)
- {
- Program.Compare(66, 579);
- Console.ReadKey();
- }
- }
- }
Output
B is greater than A
If we observe the above code, for comparing two values, we have used 'if-else'. In C#, we have a special decision-making operator called ternary operator which is similar to if-else. The ternary operator compares two values and based on it, returns a value. The above program can be rewritten using the ternary operator as shown below.
B is greater than A
If we observe the above code, for comparing two values, we have used 'if-else'. In C#, we have a special decision-making operator called ternary operator which is similar to if-else. The ternary operator compares two values and based on it, returns a value. The above program can be rewritten using the ternary operator as shown below.
- using System;
- namespace Tutpoint
- {
- class Program
- {
- public static void Compare(int a, int b)
- {
- string output = a > b ? "A is greater than B" : "B is greater than A";
- Console.WriteLine(output);
- }
- static void Main(string[] args)
- {
- Program.Compare(66, 579);
- Console.ReadKey();
- }
- }
- }
If we observe this program, the code looks more concise and shorter.
What is a Ternary operator?
C# has a special decision-making operator named 'Ternary operator' used to compare two values.
The Syntax of Ternary operator is,
data_type Output_Variable = Conditional Expression? first_statement: second_statement;
Here, generally, we use data_type as var. The reason for this is that the ternary operator can return value of any data type.

Join the conversation! Your thoughts help the community grow.