C# Comparison operators

C# Comparison operators

Comparison operators (C# Relational Operators) are used to compare two values (or variables). This is important in programming, because it helps us to find answers and make decisions.

The return value of a comparison is either True or False. These values are known as Boolean values, and you will learn more about them in the Booleans chapter.

The equality and comparison operators, ==, !=, <, >, >=, and <=, work for all numeric types.

== and != test for equality and inequality of any type, return a bool value.

When using == on Value types, it compares the actual value:

int x = 3;
int y = 5;
int z = 3;
Console.WriteLine (x == y);    // False
Console.WriteLine (x == z);    // True

In the following example, we use the greater than operator (>) to find out if 8 is greater than 5:

int x = 8;
int y = 5;
Console.WriteLine(x > y); // returns True because 8 is greater than 5

A list of all C# comparison operators:

OperatorNameExample
==Equal tox == y
!=Not equalx != y
>Greater thanx > y
<Less thanx < y
>=Greater than or equal tox >= y
<=Less than or equal tox <= y

C# comparison operators - Description:

  • == : Returns true if operands are equal otherwise false.
  • != : Returns true if operands are not equal otherwise false.
  • > :   Returns true if the right operand is greater than the left operand
  • < :   Returns true if the right operand is less than the left operand
  • >= : Returns true if the right operand is greater than or equal to the left operand
  • <= : Returns true if the right operand is less than or equal to the left operand

 

The following code create a class to represent a person. class type is a reference type.

In the main method, it creates two object of persons, they both have the same time.

The == is comparing the reference not the value.

Example:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace HelloWorld
{
    class Program
    {
        class Person
        {
            public string Name;
            public Person(string n) { Name = n; }
        }
        static void Main(string[] args)
        {
            Person d1 = new Person("dani");
            Person d2 = new Person("dani");
            Person d3 = d1;

            Console.WriteLine(d1 == d2);       // False
            Console.WriteLine(d1 == d3);       // True
            Console.ReadLine();
        }       
    }
}

Output:

C# Comparison operators example