C# - Ternary / Conditional Operator Example

Here, we are going to learn about the use of a ternary conditional operator and its C# implementation.
Submitted by Nidhi, on September 10, 2020 [Last updated : March 18, 2023]

Ternary / Conditional Operator

Here we will use the ?: ternary operator, it is also known as a conditional operator. We can check conditions use this operator. Most of the "if" statement can be replaced by the ?: conditional operator.

C# program for ternary / conditional operator example

The source code to demonstrate the use of a ternary conditional operator is given below. The given program is compiled and executed successfully on Microsoft Visual Studio.

//C# Program to demonstrate the use of the 
//conditional ternary operator

using System;

class Sample {
  static void Main() {
    int num1 = 0;
    int num2 = 0;

    int large = 0;

    Console.Write("Enter num1: ");
    num1 = int.Parse(Console.ReadLine());
    Console.Write("Enter num2: ");
    num2 = int.Parse(Console.ReadLine());

    large = (num1 > num2) ? num1 : num2;

    Console.WriteLine("Large: " + large);


Enter num1: 5
Enter num2: 6
Large: 6
Press any key to continue . . .


In the above program, we created a Sample class that contains the Main() method. In the Main() method we declared three local variables num1, num2, and large initialized with 0. Then we read the values of num1 and num2.

large = (num1 > num2) ? num1 : num2;

Using the above statement, we find the largest number from num1 and num2 and assigned to the variable large. Here if condition (num1>num2) is true then the value of num1 is assigned to the variable large otherwise the value of num2 will be assigned in the variable large. Then finally we printed the value of the variable large on the console screen.

C# Basic Programs »

Comments and Discussions!

Load comments ↻

Copyright © 2024 www.includehelp.com. All rights reserved.