Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

If I override ToString, do i need to override Equals and GetHashCode as well?

Tags:

c#

.net

c#-3.0

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

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

like image 692
Dreamer Avatar asked Nov 05 '11 02:11

Dreamer


2 Answers

Overriding those three methods serve three different purposes:

  1. ToString: Output representation of the object.
  2. Equals: If two objects represent the same thing. Uses GetHashCode in it's default implementation.
  3. GetHashCode: Used for indexing of objects. Several advanced topics here including semi-uniqueness and distribution of hashvalues.

As you can see 2 and 3 are related, but 1 is separate. Unless you implement Equals to simply test if the ToString of two objects are equals, which would most likely be a mistake. :)

So the short answer has allready been given: You can override ToString without overriding the two other 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

like image 133
Gaute Løken Avatar answered Oct 04 '22 00:10

Gaute Løken


No, you don't have to override Equals and GetHashCode, they're not related to ToString

like image 36
Thomas Levesque Avatar answered Oct 04 '22 01:10

Thomas Levesque