C# Comparison Operators

In this chapter you will learn:
  • What is C# Comparison Operator?
  • How many types of Comparison Operators in C sharp?
  • How to use Comparison operators in a program?

The C# comparison operator is used to compare two operands. It returns true or false based on the comparison. The complete list of comparison operators is listed in a table.

Consider x is a variable and the value assigned the x=2 then,

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

Examples:

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();
        }
    }
}

Output

Enter first number   4
Enter second number   6
6 is greater than   4
__

You will learn more about if…else constructs in lateral session.

Summary

In this chapter, you learned about different types of C# comparison operatorsand also learned how to use it in a program. In next chapter, you will learn about  Logical Operators in C#.

More Articles

 

Share your thought



PLEASE DISABLE ADBLOCKER AND SUPPORT US!

Please support us by enabling ads on this page. Refresh

YOU DON'T LIKE ADS, WE ALSO DON'T LIKE ADS!
 
But we have to show ads on our site to keep it free and updated. We have to pay huge server costs, domain costs, CDN Costs, Developer Costs, Electricity and Internet Bill. Your little contribution will encourage us to regularly update this site.