07 Feb 2024




Intermediate

In C#, understanding the distinctions between == and .Equals() is crucial for accurate object comparisons. Both operators serve different purposes:

1. == Operator:

  • The == operator is primarily used for comparing the equality of two objects.
  • Primarily used for reference equality, meaning it checks if two references point to the same memory location.
    • For value types like int, bool, etc., it directly compares the actual values.
    • For reference types like objects, it compares memory locations, not necessarily the objects' properties.

2. .Equals() Method:

  • The .Equals() method is used to compare the contents or the values of two objects.
  • It is inherited from the System.Object class, which means every object in C# has the .Equals() method.
  • By default, it checks reference equality (like ==), but can be overriden in derived classes for custom comparisons based on properties or fields.

Key Differences:

Feature== Operator.Equals() Method
PurposeReference equalityContent or value equality
Behavior for value typesCompares actual values directlyNot applicable
Behavior for reference typesCompares memory locationsCompares references, often overridden for custom behavior
PerformanceGenerally fasterSlower due to method call overhead

📝Additional Notes:

  • For null checks, .Equals() is typically preferred as it includes them inherently. Use ReferenceEquals for explicit reference comparison without null checks.
  • == for value types is generally faster, but use .Equals() for custom comparisons.
  • For primitive types like int and bool, == and .Equals() behave identically as they are value types.

Example 1:

using System;

class Program
{
    static void Main(string[] args)
    {
        string str1 = "hello";
        string str2 = "hello";

        // String interning may (not guaranteed to) make them point to the same memory:
        Console.WriteLine(str1 == str2);  // Output: true

        // `.Equals()` compares content regardless of interning:
        Console.WriteLine(str1.Equals(str2)); // Output: true

        // Custom objects need overridden `.Equals()` for value comparison:
        MyClass obj1 = new MyClass(10);
        MyClass obj2 = new MyClass(10);

        // Default `.Equals()` compares references (false in this case):
        Console.WriteLine(obj1 == obj2);

        // Overriding `.Equals()` to compare values:
        Console.WriteLine(obj1.Equals(obj2)); // Output: false (before overriding)

        // Now comparison returns true:
        // Override Equals method in MyClass to perform value comparison
        // Now comparison returns true:
        Console.WriteLine(obj1.Equals(obj2)); // Output: true (after overriding)
    }
}

class MyClass
{
    public int Value { get; set; }

    public MyClass(int value)
    {
        this.Value = value;
    }

    // Override Equals method to perform value comparison
    public override bool Equals(object obj)
    {
        if (obj == null || !(obj is MyClass))
            return false;

        MyClass other = (MyClass)obj;
        return this.Value == other.Value;
    }
}

Explanation:

  • In the code snippet, str1 and str2 are compared using both == and .Equals() methods. Since strings are immutable in C#, and string interning may occur, both comparisons return true. However, == may not always return true for different string literals due to interning, so it's safer to use .Equals() for string comparison.

  • Then, two instances of the MyClass object are created, obj1 and obj2, with the same Value property. By default, the == operator compares references, not values, so obj1 == obj2 returns false.

  • To enable value comparison for MyClass instances, the Equals() method is overridden within the MyClass class. In the overridden Equals() method, it checks whether the passed object is of type MyClass and compares the Value properties of both instances. After overriding Equals(), obj1.Equals(obj2) returns true, indicating that both instances have the same value.

This example highlights the importance of overriding the Equals() method for custom objects to enable proper value comparison, especially when using the == operator compares references, not values.

👉Read More Examples of the difference between == and .Equals() in C#.