07 Feb 2024
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.
- For value types like
2. .Equals() Method:
- The
.Equals()method is used to compare the contents or the values of two objects. - It is inherited from the
System.Objectclass, 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 |
|---|---|---|
| Purpose | Reference equality | Content or value equality |
| Behavior for value types | Compares actual values directly | Not applicable |
| Behavior for reference types | Compares memory locations | Compares references, often overridden for custom behavior |
| Performance | Generally faster | Slower due to method call overhead |
📝Additional Notes:
- For null checks,
.Equals()is typically preferred as it includes them inherently. UseReferenceEqualsfor explicit reference comparison without null checks. ==for value types is generally faster, but use.Equals()for custom comparisons.- For primitive types like
intandbool,==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,
str1andstr2are compared using both==and.Equals()methods. Since strings are immutable in C#, and string interning may occur, both comparisons returntrue. However,==may not always returntruefor different string literals due to interning, so it's safer to use.Equals()for string comparison. -
Then, two instances of the
MyClassobject are created,obj1andobj2, with the sameValueproperty. By default, the==operator compares references, not values, soobj1 == obj2returnsfalse. -
To enable value comparison for
MyClassinstances, theEquals()method is overridden within theMyClassclass. In the overriddenEquals()method, it checks whether the passed object is of typeMyClassand compares theValueproperties of both instances. After overridingEquals(),obj1.Equals(obj2)returnstrue, 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#.