0

When I examined a project(my company codes). I looked this:

public override int GetHashCode()
{
    unchecked
    {
        int result = 17;
        result = result * 23 + ((connection != null) ? this.connection.GetHashCode() : 0);
        return result;
    }
}

actually, I have seen GetHashCode() first time. I ran a little about it. But I cant understand why they used it in this code line and for connection?

Is there a special reason? What is the logic to use getHashCode for connection?

Thanks.

AliRıza Adıyahşi
  • 15,658
  • 24
  • 115
  • 197

2 Answers2

2

GetHashCode should be used if you know a good way to generate fast and well distributed hashkeys for an object.

This is useful when you want to store the object in dictionaries and such. Better hashing means better efficiency in those datastructures.

Otherwise the base GetHashCode() is used. Which is suboptimal in a lot of cases.For some details on using the GetHasCode override combined with Equals override see;

http://msdn.microsoft.com/en-us/library/ms173147(v=vs.80).aspx

IvoTops
  • 3,463
  • 17
  • 18
1

That GetHashCode can be used to quickly identify whether two instances appear to be "the same" (different hashcode = different instance; same hashcode could mean same instance).

Apparently that "connection" field is important in deciding the identity of your object.

Hans Kesting
  • 38,117
  • 9
  • 79
  • 111