Fernanda Brum Lousada
Fernanda Brum Lousada

Reputation: 371

Cannot convert from base to generic T

I need to convert List<Base> objects to a List<T> objects, where T is one of the types that derivate from Base, I know that for sure. But the compiler says:

"Cannot convert from 'Base' to 'T'"

Some code:

var rObj = JsonConvert.DeserializeObject<RootObject>(json);

List<T> list = new List<T>();

var ent = rObj.Entities; // Entities is List<Base>

foreach (var i in ent)
    list.Add(i); // here I know that each i is a Base descendent, but the compiler reclams

How can I get this? How can I recover derived instances from List, since I only have T information at this runtime moment?

Thanks!

Upvotes: 0

Views: 46

Answers (1)

Scott Hannen
Scott Hannen

Reputation: 29222

The definition, List<Base>, does not indicate that any of the items in the list are derived from Base. The only thing the list enforces is that its items are Base or its derived classes. It doesn't enforce that any item is an inherited class or that it is any specific inherited class. (You know what type the list contains, but the compiler doesn't.)

You can do this:

listOfT.AddRange(listOfBase.OfType<T>());

That will add whichever items are of type T to the List<T>.

If you're really certain that every item in the list can be cast to T then you could do

listOfT.AddRange(listOfBase.Cast<T>());

Upvotes: 1

Related Questions