Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

should all c# classes implement Equals and GetHashCode?

Tags:

c#

should all c# classes override Equals and GetHashCode? For correctness

like image 206
DayTwo Avatar asked May 06 '26 16:05

DayTwo


2 Answers

No, they already do.

Whether you have to override them, is up to how it will be used. In most cases, it is not needed.

like image 166
leppie Avatar answered May 08 '26 06:05

leppie


All classes already inherit these methods from the base class, System.Object.

You can choose to override the methods in derived classes if you need to be able to compare two instances of an object beyond simple reference equality, otherwise it's not necessary.

Remember, however, that if you choose to override one of them, you also need to override the other in order to ensure that Hashtables and dictionary keys, among other things, work properly with you derived class. The GetHashCode method needs to reflect the same logic as the Equals method. See here for more explanations and examples:

http://msdn.microsoft.com/en-us/library/bsc2ak47.aspx

and

http://msdn.microsoft.com/en-us/library/system.object.gethashcode.aspx

like image 38
Cody Gray Avatar answered May 08 '26 06:05

Cody Gray



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!