How to make a list hold all the different implementations of generic interface?
e.g
public class Animal { // some Animal implementations }
public class Dog : Animal { // some Dog implementations }
public class Snake : Animal { // some Snake implementations }
public interface ICatcher<T> where T: Animal
{
// different animals can be caught different ways.
string Catch(T animal);
}
public class DogCatcher : ICatcher<Dog>
{
string Catch(Dog animal) { // implementation }
}
public class SnakeCatcher : ICatcher<Snake>
{
string Catch(Snake animal) { // implementation }
}
I want to hold all the catcher in a list something like,
public class AnimalCatcher
{
// this will hold the catching method an animal catcher knows (just something similar)
public IEnumerable<ICatcher<Animal>> AnimalCatcher = new List<ICatcher<Animal>>
{
new DogCatcher(),
new SnakeCatcher()
}
}
I know that it is something to deal with generic modifiers in c# (Covariance, Contravariance and Invariance) but unable to get it working.
Tried: adding 'out' in
public interface ICatcher<out T> where T: Animal
{
// different animals can be caught different ways.
string Catch(T animal);
}
but gives a compile time error :
"The type parameter 'T' must be contravariantly valid on 'ICatcher.Catch(T)'. 'T' is covariant."
What am i doing wrong?
new DogCatcher()
andnew SnakeCatcher()
) toICatcher<Animal>
? – Eric Wu