2

Possible Duplicate:
C# difference between == and .Equals()
== vs Equals in C#

Hi, In terms of general use, is == the same as Equals()? I mean, both just return true if he objects are the same (reference)?

Community
  • 1
  • 1
Mocco
  • 1,183
  • 2
  • 12
  • 25
  • 3
    As an aside, there is no such thing as "general" use; computers are binary, it's one way or another! – joshcomley Mar 08 '11 at 09:29
  • 1
    I voted for reopen, since the question mentioned as a duplicate does *not* talk about the conceptual difference between `==` and `Equals`. Instead, it deals with one specific case of operand evaluation order, which is a different topic. – Heinzi Mar 08 '11 at 09:38
  • @Heinzi: You're right. It's probably a duplicate of [this question](http://stackoverflow.com/questions/814878/c-difference-between-and-equals) instead. – Cody Gray - on strike Mar 08 '11 at 09:41
  • @Cody: Good point. Is there any possibility to *take back* a reopen vote? – Heinzi Mar 08 '11 at 09:55
  • @Heinzi: No, unfortunately not. I've made many such errors myself. But they fade away after a couple of days if no one else agrees. (Coincidentally, the *original* proposed duplicate was originally closed a duplicate of the question I found.) – Cody Gray - on strike Mar 08 '11 at 09:56

3 Answers3

4

No, they serve different purposes They can both be customized by inheriting classes which means that theoritically A==B could return a different value than A.Equals(B) but the main difference is that == is resolved at compile time whereas Equals is resolved at runtime

vc 74
  • 37,131
  • 7
  • 73
  • 89
1

First question, no it's not.

Second question, yes. If

  • the thing compared are reference types that both are of the same type
  • if they point to the same reference
  • the == operator is not overloaded
  • the Equals method is not overridden

than yes, == can be treated as same with Equals.

SWeko
  • 30,434
  • 10
  • 71
  • 106
1

Equals and == are used for different purposes:

Because Equals is a virtual method, any class can override its implementation. Any class that represents a value, essentially any value type, or a set of values as a group, such as a complex number class, should override Equals. [...]

When a type is immutable, that is, the data that is contained in the instance cannot be changed, overloading operator == to compare value equality instead of reference equality can be useful because, as immutable objects, they can be considered the same as long as they have the same value. It is not a good idea to override operator == in non-immutable types.

Heinzi
  • 167,459
  • 57
  • 363
  • 519