user3041702 user3041702 - 2 years ago 80
C# Question

Cannot convert from List<Bar> to List<Foo>

I have a set up like this:

abstract class Foo {}
class Bar : Foo {}

and a method elsewhere of this form:

void AddEntries(List<Foo>) {}

I am trying to call this method using a list of objects of type

List<Bar> barList = new List<Bar>()

but this gives me the error:

cannot convert from List<Bar> to List<Foo>

Is there anyway around this problem? I Need to keep the method definition using the abstract class.

Answer Source

You could make your AddEntries generic and change it to this

void AddEntries<T>(List<T> test) where T : Foo
    //your logic 

Have a look at Constraints on Type Parameters for further information.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download