Equals() vs == in C#

What is the difference between Equals() and ==?

In C#, both the equals() method and the == operator are used to compare objects, but they have different purposes and behavior. Understanding the difference between the two is crucial when comparing objects or primitive types.

== Operator

The == operator is used to compare the values of primitive types (e.g., int, bool, char). When applied to reference types, it checks whether both operands refer to the same object in memory (i.e., reference equality).

Example: Using == Operator

string a = "Hello";
string b = "Hello";
string c = new string("Hello".ToCharArray());

Console.WriteLine(a == b);  // Output: True (value comparison)
Console.WriteLine(a == c);  // Output: True (value comparison)
Console.WriteLine((object)a == (object)c);  // Output: False (reference comparison)
        

In this example, a == b returns true because the == operator performs value comparison for strings. However, (object)a == (object)c returns false because it compares references, and a and c refer to different objects in memory.

Equals() Method

The equals() method is used to determine whether two object instances are equal based on their content (value comparison). For value types, it compares the values of the objects, and for reference types, it can be overridden to compare object content instead of reference equality.

Example: Using Equals() Method

string a = "Hello";
string b = "Hello";
string c = new string("Hello".ToCharArray());

Console.WriteLine(a.Equals(b));  // Output: True (value comparison)
Console.WriteLine(a.Equals(c));  // Output: True (value comparison)
Console.WriteLine((object)a.Equals((object)c));  // Output: True (value comparison)
        

In this example, a.Equals(b) returns true because equals() compares the content of the strings. Similarly, (object)a.Equals((object)c) still performs value comparison, as the equals() method is overridden for the string class.

Difference Between Equals() and ==

Although both equals() and == are used to compare objects, there are significant differences between them:

Aspect equals() ==
Purpose Compares object content (value comparison). For value types, compares values. For reference types, compares object references (reference equality).
Overridable Can be overridden in custom classes to compare object content. Cannot be overridden for reference types (except for built-in types like string).
Usage Used for value and content comparison. Used for both value comparison (primitive types) and reference comparison (reference types).

Key Points to Remember

  • The equals() method compares object content (value comparison) and can be overridden in custom classes.
  • The == operator compares values for primitive types and object references for reference types.
  • For built-in types like string, == is overridden to perform value comparison.