Search code examples
c#gethashcode

How do you write a GetHashCode method for an object made of a string and a collection of int32?


There is a class of Products:

public class ProductWithFeatures
{
    public string Name { get; set; }
    public ICollection<Feature> Features { get; set; }
}

public class Feature
{
    public int Id { get; set; }
    
    public Feature(int Id)
    {
        this.Id = Id;
    }
}

I want to write an IEqualityComparer for this (i already have one for Feature).

The one for Feature is like this:

public class FeatureComparer : IEqualityComparer<Feature>
{
    public bool Equals(Feature x, Feature y)
    {
        return x.Id == y.Id;
    }

    public int GetHashCode(Feature obj)
    {
        return obj.Id;
    }
}

And what i wrote so far on the other one is this:

public class ProductComparer : IEqualityComparer<LinqHomework.ProductWithFeatures>
        {
            public bool Equals(ProductWithFeatures x, ProductWithFeatures y)
            {
                return x.Name == y.Name && LinqHomework.FeatureComparer.Equals(x.Features, y.Features);
            }

            public int GetHashCode(ProductWithFeatures obj)
            {
    
            }
        }

I can't find an answer anywhere about this. Does anybody know how to write it?


Solution

  • It's really up to you. I personally would go for something like

    public int GetHashCode( ProductWithFeatures obj )
    {
        string toHash = obj.Name;
        foreach( var feature in obj.Features )
            toHash += feature.GetHashCode();
    
        return toHash.GetHashCode();
    }
    

    It's not the nicest code ever, but it does what it's supposed to do.