C# Interview Question #10

What is the difference between == and .Equals() in C#?

C# & .NET Fundamentals Junior Beginner

Quick Interview Answer

Both can compare values, but the exact behavior depends on the type and how equality is implemented.

Detailed Explanation

Both can compare values, but the exact behavior depends on the type and how equality is implemented.

The == operator can be overloaded. For many reference types, the default behavior is reference equality, although types such as string overload == to perform value-based comparison.

Equals() is a virtual method inherited from object and can be overridden to define logical equality. When custom value equality is implemented, GetHashCode() should normally be implemented consistently as well.

C# records provide value-based equality by default.

Code Example

string a = "Hello";
string b = "Hello";

Console.WriteLine(a == b);       // True
Console.WriteLine(a.Equals(b)); // True