Search code examples
.nethashcodegethashcode

Generating Hash Code for Object


I have a custom object (DataPointCollection) with two Integer properties and a Guid property. I want that object to generate a HashCode so that no two objects with the same values in those properties are added to a HashSet. I know I need to override the GetHashCode() method, but how do I do generate a hash code to accomplish this?

Here's how I want to use it.

Dim dataPointCollections As New HashSet(Of DataPointCollection)()

For Each row As DataRow In myDataSet.Tables(0).Rows

  Dim dataPointCollection As New DataPointCollection()
  dataPointCollection.ProjectID = row("ProjectID") 'Integer'
  dataPointCollection.RoleID = row("RoleID") 'Integer'
  dataPointCollection.ResourceGUID = row("ResourceGUID") 'Guid'

  If Not dataPointCollections.Contains(dataPointCollection) Then
    dataPointCollections.Add(dataPointCollection)
  End If

Next

I'm open to other ideas, but I thought this might be faster than doing a LINQ query on a collection of objects (there could be a very large number of these objects).


Solution

  • You need to override both GetHashCode and Equals - it's the combination of the two which will be used by the HashSet.

    Your equality check should:

    • Check that the other object is of the same type as this object (it's simpler if DataPointCollection is a sealed type; equality and inheritance are messy when combined)
    • Compare the three fields for equality

    Your hash code check needs to combine the three fields; the result doesn't have to be unique; for performance it's better if two unequal objects have a different hash code, but that's not required. The absolute requirement is that two equal objects do have the same hash code. I'd do something like this (C#, but easy to convert to VB):

    public override int GetHashCode()
    {
        int hash = 17;
        hash = hash * 31 + projectId;
        hash = hash * 31 + roleId;
        hash = hash * 31 + resourceGuid.GetHashCode();
        return hash;
    }