0

Sorry if my question is poorly worded, but it is precisely because I don't know how to word the question that I can't easily search this on google.

Basically I just want to combine these two functions but couldn't find a generic example with a generic inside the of a parameter? What do I call the bracketed area of a parameter? is type specifier a real term?

anyway I want to combine them into one function that takes two keyvaluepair<int, T> but I can't seem to get the syntax right.

public class BinarySearchComparers:IComparer<KeyValuePair<int, string>>, IComparer<KeyValuePair<int, byte>>
  {
    public int Compare(KeyValuePair<int, string> x, KeyValuePair<int, string> y)
    {
      return x.Key.CompareTo(y.Key); 
    }
    public int Compare(KeyValuePair<int, byte> x, KeyValuePair<int, byte> y)
    {
      return x.Key.CompareTo(y.Key);
    }
  }
John Saunders
  • 160,644
  • 26
  • 247
  • 397
James Joshua Street
  • 3,259
  • 10
  • 42
  • 80
  • What does "with a generic inside the of a parameter" mean? – Cédric Bignon Jul 23 '13 at 01:18
  • 1
    If I correctly understand what you're trying to do, I'm not sure if you can do this. Specifying a generic type `T` to represent `string`, _and_ a second generic type `U` to represent `byte` in your example would lead to a "cannot implement both because they may unify for some type parameter substitutions". See [this](http://higherlogics.blogspot.ca/2011/11/type-unification-forbidden-more-cclr.html) and [this](http://stackoverflow.com/questions/7664790/why-does-the-c-sharp-compiler-complain-that-types-may-unify-when-they-derive-f). – Chris Sinclair Jul 23 '13 at 01:21

1 Answers1

0
public class BinarySearchComparers<T> : IComparer<KeyValuePair<int, T>>  // Declares a generic type
{
    public int Compare(KeyValuePair<int, T> x, KeyValuePair<int, T> y)
    {
        return x.Key.CompareTo(y.Key); 
    }
}

Is it what you want?

Update

Given Chris Sinclair understanding of your question, the solution might be:

public class BinarySearchComparers<U, T> : IComparer<KeyValuePair<U, T>>  // Declares a generic type
    where U : IComparable<U>  // Restricts the type U to implémentations of IComparable<U> (necessary to call CompareTo)
{
    public int Compare(KeyValuePair<U, T> x, KeyValuePair<U, T> y)
    {
        return x.Key.CompareTo(y.Key); 
    }
}
Cédric Bignon
  • 12,892
  • 3
  • 39
  • 51