2

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?

Sam Leach
  • 12,746
  • 9
  • 45
  • 73
madsbirk
  • 73
  • 6

1 Answers1

1

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.

Community
  • 1
  • 1
Brendan Hill
  • 3,406
  • 4
  • 32
  • 61
  • Apart from the fact that I A needs to be an interface for this to work, this is the solution I am looking for. And I can just declare an interface above A that has an out. Thank you! – madsbirk Oct 28 '13 at 21:13