Algorithm


The ternary conditional operator (? :) in C# is a concise way to express an if-else statement. It is also known as the conditional operator or the ternary operator because it takes three operands. The general syntax is as follows:

csharp
condition ? expression_if_true : expression_if_false;
 

Here's how it works:

  • If the condition is true, the value of the entire expression is the result of expression_if_true.
  • If the condition is false, the value of the entire expression is the result of expression_if_false.

 

Code Examples

#1 C# Programming Ternary Operator

Code - C# Programming

using System;

namespace Conditional
{
	class Ternary
	{
		public static void Main(string[] args)
		{
			int number = 2;
			bool isEven;

			isEven = (number % 2 == 0) ? true : false ;  
			Console.WriteLine(isEven);
		}
	}
}
Copy The Code & Try With Live Editor

Output

x
+
cmd
True

#2 Use ternary operator

Code - C# Programming

if (a > b)
{
	result = "a is greater than b";
}
else if (a  <  b)
{
	result = "b is greater than a";
}
else
{
	result = "a is equal to b";
}
Copy The Code & Try With Live Editor
Advertisements

Demonstration


C# Programming ternary (? :) Operator