0

I try to implement IEqualityComparer:

class AddressComparer : IEqualityComparer<Address>
{
    #region IEqualityComparer<Address> Members

    public bool Equals(Address x, Address y)
    {
       return (x.CurrentBuildingNumber == y.CurrentBuildingNumber) && (x.CurrentBuildingLetter == y.CurrentBuildingLetter);
    }

    public int GetHashCode(Address obj)
    {
        return obj.StreetCode1 + obj.StreetCode2 + obj.BuildingNumber1 + obj.BuildingNumber2;
    }

    #endregion
}

Here is Address class:

public class Address : IComparable
{   
    public int StreetCode1   { get; set; }
    public int BuildingNumber1 { get; set; }
    public string BuildingLetter1 { get; set; }

    public int StreetCode2 { get; set; }
    public int BuildingNumber2 { get; set; }
    public string BuildingLetter2 { get; set; }

}

The AddressComparer works perfect if properies StreetCode and BuildingNumber of the Address class are integers.

But what if I need to change the type of properies StreetCode and BuildingNumber in the Address class to string:

public class Address : IComparable
{   
    public string StreetCode1 { get; set; }
    public string BuildingNumber1 { get; set; }
    public string BuildingLetter1 { get; set; }

    public string StreetCode2 { get; set; }
    public string BuildingNumber2 { get; set; }
    public string BuildingLetter2 { get; set; }

}

Here is imlementation of the new AddressComparer:

class AddressComparer : IEqualityComparer<Address>
{
    #region IEqualityComparer<Address> Members

    public bool Equals(Address x, Address y)
    {
       return String.Compare(x.CurrentBuildingNumber, y.CurrentBuildingNumber) && (x.CurrentBuildingLetter, y.CurrentBuildingLetter)
    }

    public int GetHashCode(Address obj)
    {
        //how to implement?
    }

    #endregion
}

How do I implement GetHashCode method if my properies are strings?

Michael
  • 13,950
  • 57
  • 145
  • 288
  • 2
    They very first question you should answer is why you need to implement GetHashCode to begin with, if only to satisfy the compiler that sees you implementing Equals, then that's one thing, but if it is to use it as a key into a dictionary or similar, then you should **strongly** consider making the type immutable. – Lasse V. Karlsen Nov 06 '17 at 13:34
  • You should provide the same members in GetHashcode as in `Equals`. As you have only strings simply rely on the hashcode of the string-properties. Have you read this: https://stackoverflow.com/questions/263400/what-is-the-best-algorithm-for-an-overridden-system-object-gethashcode – MakePeaceGreatAgain Nov 06 '17 at 13:34

0 Answers0