madsbirk
madsbirk

Reputation: 73

Calling a method with an instance of derived class of derived generic type

Okay, so I have classes

class B<T> : A<T>
class L : K

and a method

void Method(A<K> a) {...}

What I would like to do is this

var b = new B<L>();
Method(b); //error

But it is not possible to b to the correct type. Indeed it is not possible to make this cast

A<K> t = new A<L>(); //error

I would really like to not have to change the internals of Method. I have no problems making changes to B and/or L. Do I have any options for making some sort of workaround? I guess it should be possible for Method to execute all of its method calls etc. on b, since B derives from A and L derives from K?

Upvotes: 2

Views: 77

Answers (1)

Brendan Hill
Brendan Hill

Reputation: 3732

Assuming you're using C# 4.0+, you need to declare the type parameter of A to be covariant:

public class A<out T> where T : K
{
}

This should allow you pass a variable of B to a parameter of A

Some more info:

Understanding Covariant and Contravariant interfaces in C#

Obviously in OOP you can pass a derived type to the parameter declared as a base type (that's the whole point). Covariance allows the same thing - but for type parameters, which is what you need in this case.

Upvotes: 1

Related Questions