-5

I started to learn about Operator overloading, and in an example code that I found those two methods were (public override bool equals(object obj) and public override int gethashcode()). I didn't understand why they are there because when I dubugged this program, I didn't see that the compiler goes into them. I don't know what they are doing or what am I overriding.

Can someone please help me and explain it?

Dante May Code
  • 11,177
  • 9
  • 49
  • 81
IdoShamriz
  • 63
  • 1
  • 3
  • 7

2 Answers2

1

Most types in .NET derive from the type System.Object, simply called object in C#. (E.g. interfaces don't, however their implementations do.)

System.Object declares the methods Equals and GetHashCode as well as other members. (Note: The case matters in C#). The types you create automatically inherit these methods.

The task of Equals is to compare an object to another. The default implementation for reference types is to compare the references. If you want to change this behavior, you will have to override this method.

GetHashCode calculates the hash code of an object and is used in hash tables. For instance the types Dictionary<TKey,TValue> and HashSet<T> make use of it. See Hashtable and Dictionary Collection Types. If you override Equals, you have to override GetHashCode as well in order to keep consistency.

Olivier Jacot-Descombes
  • 104,806
  • 13
  • 138
  • 188
0

It is best to first refer the documentation.

Object.Equals -> Determines whether the specified object is equal to the current object.

The type of comparison between the current instance and the obj parameter depends on whether the current instance is a reference type or a value type. If the current instance is a reference type, the Equals(Object) method tests for reference equality, and a call to the Equals(Object) method is equivalent to a call to the ReferenceEquals method. Reference equality means that the object variables that are compared refer to the same object.

Object.GetHashCode -> Serves as a hash function for a particular type.

A hash code is a numeric value that is used to identify an object during equality testing. It can also serve as an index for an object in a collection. The GetHashCode method is suitable for use in hashing algorithms and data structures such as a hash table.

Why are they overrides > All types in c# are derived from System.Object. They are overrides to give capability to derive class to provide alternate/suitable implementation of these functions if needed. Otherwise default implementation (in System.Object should be sufficient).

Tilak
  • 30,108
  • 19
  • 83
  • 131