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?
No, it should not. It is potentially unsafe:
If you were to call
Getwithnew List<B>(), it would be unsafe, as you’d be inserting instances ofCinList<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 changeList<A>toIEnumerable<A>instead and it’ll work.