07 Feb 2024
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:
-
object1andobject2are both references to the same string object"Hello World!". When you assignobject1toobject2, both references point to the same memory location. -
==Operator:- In this context,
==compares the references ofobject1andobject2. - Since both
object1andobject2point to the same string object, the==operator returnstrue.
- In this context,
-
.Equals()Method:- By default, the
.Equals()method compares references. - Since
object1andobject2reference the same object,.Equals()returnstrue.
- By default, the
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:
-
We define a
Personclass withNameandAgeproperties, along with custom equality logic implemented through theEquals()method. -
We create three
Personobjects:person1,person2, andperson3.person1andperson2have the same name and age.person3has different name and age compared toperson1.
-
Using
==:person1 == person2compares references, so it returnsfalsebecauseperson1andperson2are separate instances.person1 == person3also compares references, so it returnsfalsefor the same reason.
-
Using
.Equals():person1.Equals(person2)compares theNameandAgeproperties ofperson1andperson2, returningtruebecause they have the same name and age.person1.Equals(person3)compares theNameandAgeproperties ofperson1andperson3, returningfalsebecause 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
Personclass, overridingGetHashCode()is essential when you overrideEquals()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 theNameandAgeproperties of thePersonobject. 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 theEquals()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 byEquals()) 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 thePersonclass, enabling proper usage in hash-based collections.