Possible Duplicate:
Casting List<> of Derived class to List<> of base class
The title may not make good sense. See the code:
class Person {}
class Manager : Person {}
class PaymentCalculator<T> where T : Person
{
public double Calculate(T person)
{
return 0; // calculate and return
}
}
class Calculators : List<PaymentCalculator<Person>>
{
public Calculators()
{
this.Add(new PaymentCalculator<Person>());
this.Add(new PaymentCalculator<Manager>()); // this doesn't work
PassCalculator(new PaymentCalculator<Person>());
PassCalculator(new PaymentCalculator<Manager>()); // this doesn't work
}
public void PassCalculator(PaymentCalculator<Person> x)
{ }
}
The two lines in the code marked as “this doesn’t work” won’t compile.
I can work around the issue, but it doesn’t seem my intent is wrong. Or, is it?
Even though
Managerinherits fromPerson,PaymentCalculator<Manager>doesn’t inherit fromPaymentCalculator<Person>. It would work ifPaymentCalculator<T>was contravariant, but classes can’t be contravariant in .NET (only interfaces and delegates can be contravariant).A possible solution to your problem would be to declare a contravariant interface like this:
Make
PaymentCalculator<T>implements theIPaymentCalculator<T>interface:And make the
Calculatorsclass inherit fromList<IPaymentCalculator<Person>>With these changes, it should work as you expect.