CSharp - Operator Comparison Operators

Introduction

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 = 1;
int y = 2;
int z = 1;
Console.WriteLine (x == y);         // False
Console.WriteLine (x == z);         // True

When using == operator on reference types, by default, it is comparing the reference not the actual value.

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.

Demo

using System;

class Person//  ww w .ja va 2s .  c  om
{
       public string Name;
       public Person (string n) { Name = n; }
}

class MainClass
{
   public static void Main(string[] args)
   {

     Person d1 = new Person ("John");
     Person d2 = new Person ("John");
     Console.WriteLine (d1 == d2);       // False
     Person d3 = d1;
     Console.WriteLine (d1 == d3);       // True

   }
}

Result