开发者

Overloading operator == to check euqity of two objects

Yesterday I asked about using ov开发者_运维问答erloading operators and nobody mentioned that its quite common and often used to check equity of two objects like strings, colors..

Also in this case it is correct to overload == if my types represent some objects that could be checked for equity of their fields etc. Sure I do not mean checking whether the variables point to the same object.


Yes, it's reasonable to overload the == operator (and != at the same time, of course).

You need to be aware that it is overloading rather than overriding, so if you ever have:

object first = ...;
object second = ...;

if (first == second)

that will check for reference equality regardless of what you've done.


You can basically decide yourself what equity means. If it's to you that some fields are the same, then sure, check for that.


In my opinion is better to use == to check for reference equality and use .Equals(Object obj) for custom equality.

That way you will have two ways of comparing instead of one.

Anyway take in mind that if you redefine Equality you should redefine the GetHashCode() too so two objects that are equal return the same hash code.


Not quite sure what your question is, in that you seem to have answered it yourself. You can overload operator== etc to check that two objects are the same, so in your examples of strings or colours, that two strings have the same actual contents, or that two colours have the same RGB values. As you say, this is distinct from two variables pointing at the same object. You might want to check out the MSDN section

Operator Overloading Tutorial

for more information on overloading.

Similar question with more information, including a list of the operators that you can overload: why C# not allow operator overloading?

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜