Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Unable to cast Generic List to Custom List type

I have a two classes:

public class MyClass
{
    public int Foo { get; set; }
    public string Bar { get; set; }
}

public class MyList : List<MyClass>
{
}

In other code, I am creating instances of MyClass for each record from a DB, and I would like to return them all in a MyList instance:

var records = _repository.GetRecords();
return (MyList) records.Select(x => x.ConvertTo<MyClass>()).ToList();

The code compiles fine but it is throwing a runtime InvalidCastException:

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

I don't understand why this error is happening because MyList is a List<MyClass>.

I found some related questions which all talk about covariance. This question was the most similar to my problem but I don't know how to adapt the answer to solve my problem.

My Question:
How can I build a MyList instance out of the DB records?

I am using C# and .NET 4.0

like image 708
Jesse Webb Avatar asked May 10 '13 17:05

Jesse Webb


1 Answers

Every MyList is a List<MyClass>, but not every List<MyClass> is a MyList. For example, if you had a custom property on MyList, Linq's ToList method would have no knowledge of it.

You could create a new MyList by using the List<T> copy constructor:

return new MyList(records.Select(x => x.ConvertTo<MyClass>()).ToList());

EDIT

As @ekolis estutely noticed, you need to explicitly "inherit" the List<T> copy constructor:

public class MyList : List<MyClass>
{
    public MyList(IEnumerable<MyClass> list)
        : base(list)
    {
    }
}

I would also step back and see if you really need a MyList class, or if you can just use List<MyClass> (or even just IEnumerable<MyClass>).

like image 193
D Stanley Avatar answered Oct 03 '22 16:10

D Stanley