I have 2 classes A
and B
. B
inherits from A
. If I have a method like
void works(A aType)
I can pass a B
type object through just fine. However, a method like void fails(List<A> aListType)
fails for a List<B>
type with Visual Studio complaining that it can't convert between List<A>
and List<B>
. I can resolve this with generics, but why does it fail in the first place? Also, should I just be using generics instead?
Here's a basic example:
using System.Collections.Generic;
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
B bType1 = new B();
works(bType1); // This works
List<B> bListType1 = new List<B>();
works(bListType1); // This works
List<B> bListType2 = new List<B>();
fails(bListType2); // This fails
}
static void works(A aType)
{
return;
}
static void works<T>(List<T> aListType) where T : A
{
return;
}
static void fails(List<A> aListType)
{
return;
}
}
class A
{
}
class B : A
{
}
}