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;
....
}
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>();
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With