C# has comparison operators which are used when comparing values or references of variables. These operators yield boolean results. Values yielded by comparison expressions are either true if the comparison is, in fact, true, and false if the comparison is false. These comparison operators are commonly used in if statements and testing if the loop should continue or stop. The comparison operators are the key to making your programming decide and think.

Below shows a list of comparison operators in C#.

Operator Category Example Result
== Binary var1 = var2 == var3 var1 is assigned true if var2 is
equal to the value of var3,
false otherwise
!= Binary var1 = var2 != var3 var1 is assigned true if var2 is not
equal to the value of var3,
false otherwise
< Binary var1 = var2 < var3 var1 is assigned true if var2 is
less than the value of var3,
false otherwise
> Binary var1 = var2 > var3 var1 is assigned true if var2 is
greater than the value of var3,
false otherwise
<= Binary var1 = var2 <= var3 var1 is assigned true if var2 is
less than or equal to the value of var3,
false otherwise
>= Binary var1 = var2 >= var3 var1 is assigned true if var2 is
greater than or equal to the value of var3,
false otherwise

The program below demonstrates the functionality of comparison operators.

using System;
 
namespace ComparisonOperators
{
    class Program
    {
        static void Main()
        {
            int num1 = 10;
            int num2 = 5;
 
            Console.WriteLine("{0} == {1} : {2}", num1, num2, num1 == num2);
            Console.WriteLine("{0} != {1} : {2}", num1, num2, num1 != num2);
            Console.WriteLine("{0} <  {1} : {2}", num1, num2, num1 < num2);
            Console.WriteLine("{0} >  {1} : {2}", num1, num2, num1 > num2);
            Console.WriteLine("{0} <= {1} : {2}", num1, num2, num1 <= num2);
            Console.WriteLine("{0} >= {1} : {2}", num1, num2, num1 >= num2);
        }
    }
}

Example 1

10 == 5 : False
10 != 5 : True
10 <  5 : False
10 >  5 : True
10 <= 5 : False
10 >= 5 : True

We first create two variables that will be compared. We initialize them with values. Then, we used each comparison operators to compare the two variables and print the result.

It is important to note that when doing comparisons, you must use the == operator instead of the = operator. The = operator is the  assignment operator and an expression such as x = y is read as assign the value  of y to x. The == operator is the equality operator which tests for equality of two  values so an expression such as x == y is read as  x is equal to y.