C# has two "equals" concepts: Equals
and ReferenceEquals
. For most classes you will encounter, the ==
operator uses one or the other (or both), and generally only tests for ReferenceEquals
when handling reference types (but the string
Class is an instance where C# already knows how to test for value equality).
Equals
compares values. (Even though two separate int
variables don't exist in the same spot in memory, they can still contain the same value.)
ReferenceEquals
compares the reference and returns whether the operands point to the same object in memory.
Example Code:
var s1 = new StringBuilder("str");
var s2 = new StringBuilder("str");
StringBuilder sNull = null;
s1.Equals(s2); // True
object.ReferenceEquals(s1, s2); // False
s1 == s2 // True - it calls Equals within operator overload
s1 == sNull // False
object.ReferenceEquals(s1, sNull); // False
s1.Equals(sNull); // Nono! Explode (Exception)