I'm trying to create a method which returns a list of whichever type the user wants. To do this I'm using generics, which I'm not too familiar with so this question may be obvious. The problem is that this code doesn't work and throws the error message Cannot convert type Systems.Collections.Generic.List<CatalogueLibrary.Categories.Brand> to Systems.Collection.Generic.List<T>
private List<T> ConvertToList<T>(Category cat)
{
switch (cat)
{
case Category.Brands:
return (List<T>)collection.Brands.ToList<Brand>();
}
...
}
But if I use IList
instead, there are no errors.
private IList<T> ConvertToList<T>(Category cat)
{
switch (cat)
{
case Category.Brands:
return (IList<T>)collection.Brands.ToList<Brand>();
}
...
}
Why can I use IList but not List in this case? collection.Brands returns a BrandCollection
type from a third party library so I don't know how that's created. Could it be that BrandCollection
may derive from IList (just guessing that it does) and so it can be converted to it but not to a normal List?
return (IList<T>)collection.Brands.ToList<T>();
? – Langmuirwhere T : Brand
(and the other categories)? – TimmsInstance argument: cannot convert from '..BrandCollection' to 'System.Collections.Generic.IEnumerable<T>'
– TimmsBrandCollection
implements non-genericIEnumerable
, you should be able to useCast<T>().ToList()
– Langmuir