Comparison operator in C#

In this article I will explain how to perform Comparison operator in C#.
  • 3338

Introduction

Comparison operator is very useful in C#. Comparison operators are basically used to compare two operands in a C# program. Comparison operator returns true or false value based on comparison. Comparison operators are used some condition statement and loop construct such as for loop, if..else.

The list of comparison operators are listed in a table.

Operator Name Example
< Less than x<5 (returns true)
> Greater than x>5 (returns false)
<= Less than equal to x<=3 (returns true)
>= Greater than equal to x>=3 (returns true)
== Equal equal to x==3 (returns true)
!= Not equal to x!=3 (returns false)

Example

using System;

using System.Collections.Generic;

using System.Linq;

using System.Text;

namespace Comparison_Operator

{

    class Program

    {

        static void Main(string[] args)

        {

            int num1, num2;

            //Accepting two inputs from the user

            Console.Write("Enter first number\t");

            num1 = Convert.ToInt32(Console.ReadLine());

            Console.Write("Enter second number\t");

            num2 = Convert.ToInt32(Console.ReadLine());

 

            //Processing comparison

            //Check whether num1 is greater than or not

            if (num1 > num2)

            {

                Console.WriteLine("{0} is greater than {1}", num1, num2);

            }

            //Check whether num2 is greater than or not

            else if (num2 > num1)

            {

                Console.WriteLine("{0} is greater than {1}", num2, num1);

            }

            else

            {

                Console.WriteLine("{0} and {1} are equal", num1, num2);

            }

            Console.ReadLine();

        }

    }

}

 

The output of following program


Clipboard179.jpg

© 2020 DotNetHeaven. All rights reserved.