== is the identity test. It will return true if the two objects being tested are in fact the same object. Equals()
performs an equality test, and will return true if the two objects consider themselves equal.
Identity testing is faster, so you can use it when there's no need for more expensive equality tests. For example, comparing against null
or the empty string.
It's possible to overload either of these to provide different behavior -- like identity testing for Equals()
--, but for the sake of anybody reading your code, please don't.
Pointed out below: some types like String
or DateTime
provide overloads for the ==
operator that give it equality semantics. So the exact behavior will depend on the types of the objects you are comparing.
See also:
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…