1

I have 2 key value comparers - in both I am using key to compare, which is string. Can I use generic for the value - so instead of have 2 classes I can have only 1?

So instead of the classes below I wish I could have only 1 class

class KvpComparer : IEqualityComparer < KeyValuePair < string, T>>
{
...
}

class KvpComparer : IEqualityComparer<KeyValuePair<string, Tuple<string, string>>>
{
    public bool Equals(KeyValuePair<string, Tuple<string, string>> x, KeyValuePair<string, Tuple<string, string>> y)
    {
        return x.Key.Equals(y.Key);
    }

    public int GetHashCode(KeyValuePair<string, Tuple<string, string>> obj)
    {
        return obj.Key.GetHashCode();
    }
}

class KvpComparer2 : IEqualityComparer<KeyValuePair<string, string>>
{
    public bool Equals(KeyValuePair<string, string> x, KeyValuePair<string, string> y)
    {
        return x.Key.Equals(y.Key);
    }

    public int GetHashCode(KeyValuePair<string, string> obj)
    {
        return obj.Key.GetHashCode();
    }
}
Taisbevalle
  • 246
  • 1
  • 9
  • 19
Anand
  • 1,387
  • 2
  • 26
  • 48

1 Answers1

3

As the comparers differ only in the value type of the KeyValuePair, you could use a type parameter for the value type to generalize the two comparers into a single generic type as follows.

class KvpComparer<T> : IEqualityComparer<KeyValuePair<string,T>> where T : class
{
    public bool Equals(KeyValuePair<string,T> x, KeyValuePair<string,T> y)
    {
        return x.Key.Equals(y.Key);
    }

    public int GetHashCode(KeyValuePair<string, T> obj)
    {
        return obj.Key.GetHashCode();
    }
}
Codor
  • 17,447
  • 9
  • 29
  • 56