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
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>
).
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