Reputation: 53
I have two classes as follows, and Class A inherits from Class B.
public class A
{
public string Title { get; set; }
}
public class B: A
{
}
Then I have a function as follows which takes in a list of items of class A:
public static void Get(List<A> values)
{
// Do something
}
Now when I try to pass a list of items of Class B, into the function as follows,
private function void Test()
{
var k = new List<B>();
Get(k);
}
I get the following error message
cannot convert from 'System.Collections.Generic.List<B>' to 'System.Collections.Generic.List<A>'
Should this not work as B just inherits from A and will have the properties that A has?
I have already spent hours trying to look this up, but I have not been to figure out what I an doing wrong. How can I fix it?
Upvotes: 0
Views: 1408
Reputation: 726479
Although B
can be used everywhere an A
can be, the List<B>
and List<A>
are not covariant. However, starting with .NET 4.0 you can use a list of Derived
class in place of IEnumerable<Base>
. So if you declare your function to take IEnumerable<A>
rather than List<A>
, your code will compile.
Upvotes: 1
Reputation: 421978
No, it should not. It is potentially unsafe:
class C : A {
}
public static void Get(List<A> values)
{
values.Add(new C());
}
If you were to call Get
with new List<B>()
, it would be unsafe, as you'd be inserting instances of C
in List<B>
.
It would be safe, however, if List<T>
was a "read-only" interface, in which case covariance, which is what you are looking for, would be safe. You can change List<A>
to IEnumerable<A>
instead and it'll work.
Upvotes: 5
Reputation: 146429
B does inherit from A, but that doesn't mean that List<B>
Inherits from List<A>
You should just put the B objects into a List<A>
and pass that to the method. This is what polymorphism is all about.
private function void Test()
{
var k = new List<A>();
k.Add(new B());
k.Add(new B());
k.Add(new B());
k.Add(new B());
k.Add(new B());
k.Add(new B());
Get(k);
}
Upvotes: 0