Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Unable to cast object of type 'System.Collections.Generic.List`1[Item]' to type 'ItemList'

Tags:

c#

For some reason, my boss likes to create custom types to represent a generic list (even in most cases where his custom type has no members! I think he's just lazy and doesn't like to type the List or something but to me this is lame and is causing me many headaches per the issue below.

Point in case:

public class ItemnList : List<Item>
{
    public Personalization FindById(int id)
    {
        ...blahblah blah, this is really an extension method that should be elsewhere
    }

}

Consequently, when I'm using a standard List (mabye I hate his custom class and like to use plain .NET types like they should be used), OR maybe I'm using a LINQ expression like below, I always run into casting problems even though the custom type is inheriting from that List

private ItemList someMethod(ItemList itemList)
{
    ...
    itemList = (ItemList)items.Where(x => x.ItemType != ItemType.Car && x.ItemType != ItemType.Truck).ToList();

    return itemList;
    ....
}
like image 721
PositiveGuy Avatar asked Dec 10 '09 17:12

PositiveGuy


2 Answers

As Grzenio points out, you can't use ToList() and cast, however you could create your own extension method to create an instance of the derived type from a sequence:

public static TDerived CreateFromEnumerable<TDerived, T>(this IEnumerable<T> seq) where TDerived : List<T>, new()
        {
            TDerived outList = new TDerived();
            outList.AddRange(seq);
            return outList;
        }

So for your example you would do:

ItemList outList = itemList
    .Where(x => x.ItemType != ItemType.Car && x.ItemType != ItemType.Truck)
    .CreateFromEnumerable<ItemList, Item>();
like image 153
Lee Avatar answered Nov 15 '22 11:11

Lee


Unfortunately ToList() will return a normal list, and not ItemnList, so you can't cast it. I don't really see a reasonable workaround, it would probably be better to encapsulate the List in ItemnList, instead deriving from it.

like image 38
Grzenio Avatar answered Nov 15 '22 12:11

Grzenio