I have a collection class with an Equals method that I want to pass in a method to do equality checking between each item. Furthermore, I want to allow the delegate type to operate on superclasses of T as well as T itself:
public delegate bool EqualityComparer<T>(T x, T y);
public class Collection<T>
{
//...
public bool Equals<U>(Collection<T> other, EqualityComparer<U> eq) where T : U
{
// code using eq delegate to test equality between
// members of this and other collection
}
}
Unfortunately, the compiler borks over this (‘Collection.Equals()’ does not define type parameter ‘T’). Is there any way of specifying this type of constraint/operation?
No, I’m afraid you can’t specify a constraint like that. (I’ve wanted it too on occasion.)
You could write a static generic method with two type parameters in a non-generic class though:
and you could even make that call an instance method on the generic class if you like:
where the collection’s instance method would just be:
This uses the contravariance available for creating delegates from C# 2 onwards.