If I override ToString, do I also need to override Equals and GetHashCode?

I am sure that if I override Equals, I need to override GetHashCode to make sure Dictionary data structures, etc. work as expected.

But if I just want to override ToString, I still have to override the Equals and GetHashCode methods.

+4
source share
5 answers

Overriding these three methods is done for three different purposes:

  • ToString: The output representation of the object.
  • Equally: if two objects represent the same thing. Uses GetHashCode in its default implementation.
  • GetHashCode: used to index objects. A few additional topics here, including semi-uniqueness and hash distribution.

As you can see, 2 and 3 are connected to each other, but 1 is separate. If you don't accept Equals just check if the ToString of the two objects are equal, which is likely to be a mistake. :)

So, the short answer is already set: you can override ToString without overriding the other two methods. It is quite normal to even overload the ToString method. See DateTime for an example: http://msdn.microsoft.com/en-us/library/zdtaw1bw.aspx

+7
source

No, you do not need to override Equals and GetHashCode , they are not related to ToString

+1
source

No, you do not need to override Equals and GetHashCode, if only to redefine ToString ()

0
source

Can you redefine it only for a specific class, or do you mean to redefine it for each class / object?

 public class YourClass { // Other stuff here... public override string ToString() { // Do whatever you want here instead, or return base.ToString(); for the default behavior } } 

But no, this is not related to other methods, and you can choose what you want to override

0
source

ToString is for string representation of your object only. Nothing more.

As you said, you had to override Equals, it is best to override GetHashCode for HashTables. However, the two operations are not related.

0
source

Source: https://habr.com/ru/post/1379743/


All Articles