user3041702 user3041702 - 1 year ago 66
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
Bar


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


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