开发者

.NET, Is Equal() just ==? [duplicate]

This question already has answers here: 开发者_运维问答 Closed 11 years ago.

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)?


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


Equals and == are used for different purposes:

  • Guidelines for Overriding Equals() and Operator == (C# Programming Guide)

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.


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜