Ternary Operator in C-Sharp

Hello Friends, In this article, We are going to learn about ternary operator and nested ternary operator in c#.

ternary operator ?: is an conditional operator. It evaluates a Boolean expression and returns the result based on its boolean expression.

Syntax:

condition ? consequent : alternative

We can again use consequent and alternative as ternary operator.

The condition expression must evaluate to true or false.

If condition evaluates to true, the consequent expression evaluation will becomes result of the operation.

If condition evaluates to false, the alternative expression evaluation will becomes the result of the operation.

The consequent, alternative evaluation must be of same type.

Eample:

Let find greatest number amung two integer numbers.

using System; namespace ConsoleApp1 { class Program1 { public static void Main() { int a = 12; int b =23; int c = (a > b) ? a : b; Console.WriteLine($"Greatest among a = {a} and b = {b} is {c}."); Console.ReadKey(); } } } //Greatest among a = 12 and b = 12 is 12.

Now what will happens if a = 12 and b = 12 ?

using System; namespace ConsoleApp1 { class Program1 { public static void Main() { int a = 12; int b =23; int c = (a > b) ? a : b; Console.WriteLine($"Greatest among a = {a} and b = {b} is {c}."); Console.ReadKey(); } } } //Greatest among a = 12 and b = 23 is 23.

While both numbers are equal.

We will use here nested ternary operation like if-else statements.

using System; namespace ConsoleApp1 { class Program1 { public static void Main() { int a = 12; int b =12; string c = (a == b) ? "both are equals" : (a>b) ? "a is greater" : "b is greater"; Console.WriteLine($"Greatest among a = {a} and b = {b} is: {c}."); Console.ReadKey(); } } } //Greatest among a = 12 and b = 23 is: both are equals.

string c = (a == b) ? "both are equals" : (a>b) ? "a is greater" : "b is greater";

Explanation:

In above statements it will first evaluate a==b if condition returns true it will returns {both are equals}.

otherwise it will further evaluate expression a>b if it returns true than result will becomes {a is greater}

otherwise it will returns {b is greater} as a final result.

It will perform action like below if else statements.

string c = string.Empty; if(a==b) { c = "both are equals"; } else if (a>b) { c = "a is greater"; } else { c = "b is greater"; }

If you have any query or question or topic on which, we might have to write an article for your interest or any kind of suggestion regarding this post, Just feel free to write us, by hit add comment button below or contact via Contact Us form.


Your feedback and suggestions will be highly appreciated. Also try to leave comments from your valid verified email account, so that we can respond you quickly.

 
 

{{c.Content}}

Comment By: {{c.Author}}  On:   {{c.CreatedDate|date:'dd/MM/yyyy'}} / Reply


Categories