07 Feb 2024




Intermediate

Examples for difference between == and .Equals() in C#:

Example 1:

using System;

class Program
{
    static void Main()
    {
        object object1 = "Hello World!";
        object object2 = object1;

        // Using ==
        Console.WriteLine(object1 == object2);         // Output: true (compares references)

        // Using .Equals()
        Console.WriteLine(object1.Equals(object2));    // Output: true (compares references)
    }
}

Explanation:

  1. object1 and object2 are both references to the same string object "Hello World!". When you assign object1 to object2, both references point to the same memory location.

  2. == Operator:

    • In this context, == compares the references of object1 and object2.
    • Since both object1 and object2 point to the same string object, the == operator returns true.
  3. .Equals() Method:

    • By default, the .Equals() method compares references.
    • Since object1 and object2 reference the same object, .Equals() returns true.

In this example, both == and .Equals() produce the same result because they are comparing references, and object1 and object2 refer to the same object in memory.

Example 2:

using System;

class Person
{
    public string Name { get; set; }
    public int Age { get; set; }

    public Person(string name, int age)
    {
        Name = name;
        Age = age;
    }

    public override bool Equals(object obj)
    {
        if (obj == null || GetType() != obj.GetType())
            return false;

        Person other = (Person)obj;
        return this.Name == other.Name && this.Age == other.Age;
    }

    public override int GetHashCode()
    {
        return HashCode.Combine(Name, Age);
    }
}

class Program
{
    static void Main()
    {
        Person person1 = new Person("Alice", 30);
        Person person2 = new Person("Alice", 30);
        Person person3 = new Person("Bob", 25);

        Console.WriteLine(person1 == person2);        // Output: False (compares references)
        Console.WriteLine(person1.Equals(person2));   // Output: True (custom value-based comparison)

        Console.WriteLine(person1 == person3);        // Output: False (compares references)
        Console.WriteLine(person1.Equals(person3));   // Output: False (custom value-based comparison)
    }
}

Explanation:

  1. We define a Person class with Name and Age properties, along with custom equality logic implemented through the Equals() method.

  2. We create three Person objects: person1, person2, and person3.

    • person1 and person2 have the same name and age.
    • person3 has different name and age compared to person1.
  3. Using ==:

    • person1 == person2 compares references, so it returns false because person1 and person2 are separate instances.
    • person1 == person3 also compares references, so it returns false for the same reason.
  4. Using .Equals():

    • person1.Equals(person2) compares the Name and Age properties of person1 and person2, returning true because they have the same name and age.
    • person1.Equals(person3) compares the Name and Age properties of person1 and person3, returning false because they have different names and ages.

    In C#, the GetHashCode() method is used to generate a hash code for an object. Hash codes are numerical representations of objects that are used in hash-based collections like dictionaries and hash sets for fast retrieval and comparison.

    In the provided Person class, overriding GetHashCode() is essential when you override Equals() to maintain the consistency of equality comparison.

    Here's how the GetHashCode() method is utilized in the example:

    public override int GetHashCode()
    {
        return HashCode.Combine(Name, Age);
    }
    

    In this implementation:

    • We use HashCode.Combine() to generate a hash code based on the Name and Age properties of the Person object.
    • HashCode.Combine() is a convenience method introduced in C# 7.3 to generate hash codes for multiple values.

    The purpose of overriding GetHashCode() is to ensure that objects which are considered equal according to the Equals() method also return the same hash code. This is crucial for proper functioning of hash-based collections.

    Without overriding GetHashCode(), objects with equivalent equality comparison (as defined by Equals()) might produce different hash codes, leading to incorrect behavior when used in hash-based collections.

    Therefore, in the context of the provided example, overriding GetHashCode() ensures consistency between equality comparison and hash code generation for instances of the Person class, enabling proper usage in hash-based collections.