C# Conditional Operator with example

Conditional Operator :

A conditional operator in C#, is an operator that takes three operands (conditions to be checked), the value when the condition is true and value when the condition is false

This operator is also called as ternary operator.


Syntax : (Condition? value_true: value_false);
Example : (A > 10 ? 0 : 1);

In above example, if A is greater than 10, 0 is returned else 1 is returned. This is equal to if else conditional statements.

C# Code Example For Conditional Operator :

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace MAXFrom3
class Codelerner
static void Main(string[] args)
int a, b, c ,d;
Console.WriteLine(“Enter value of A:“);
a = Convert.ToInt32(Console.ReadLine());
Console.WriteLine(“Enter value of B:“);
b = Convert.ToInt32(Console.ReadLine());
Console.WriteLine(“Enter the value of C:“);
c = Convert.ToInt32(Console.ReadLine());

d= (a > b && a>c) ? a : (b>a && b>c) ? b: c;

Console.WriteLine(“Maximum Number is: =” + d);

Output : To see Output Run the Program


Leave a Reply

Your email address will not be published. Required fields are marked *