C# - Example of Conditional Operator

C# conditional operator example: Here, we are writing a C# - Example of Conditional Operator.
Submitted by IncludeHelp, on April 07, 2019 [Last updated : March 17, 2023]

Conditional Operator

Conditional Operator is also known as Ternary Operator which requires 3 operands, it is performed with the combination of ? and :.


(logical_test) ? true_block : false_block;

If logical_test is true"true_block" executes, else "false_block" executes.

C# program to demonstrate the example of conditional operator

Here, we are asking to input two numbers and finding the largest number.

// C# program to demonstrate example of 
// conditional operator

using System;
using System.IO;
using System.Text;

namespace IncludeHelp {
  class Test {
    // Main Method 
    static void Main(string[] args) {
      //finding largest of two numbers 
      int a;
      int b;

      //input numbers 
      Console.Write("Enter first number : ");
      a = Convert.ToInt32(Console.ReadLine());
      Console.Write("Enter second number: ");
      b = Convert.ToInt32(Console.ReadLine());

      //finding largest number
      int large = (a > b) ? a : b;

      Console.WriteLine("Largest number is {0}", large);

      //hit ENTER to exit the program


Enter first number : 100
Enter second number: 200
Largest number is 200

C# Basic Programs »

Comments and Discussions!

Load comments ↻

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