I’ve got an object, which I’ll call MyObject. It’s a class that controls a particular data row.
I’ve then got a collection class, called MyObjectCollection:
public class MyObjectCollection : List<MyObject> {}
Why can I not do the following:
List<MyObject> list = this.DoSomethingHere();
MyObjectCollection collection = (MyObjectCollection)list;
Thanks in advance.
Edit: The error is InvalidCastException
My guess is that
DoSomethingHeredoesn’t return an instance ofMyObjectCollection.Let’s get rid of all the generics etc here, as they’re not relevant. Here’s what I suspect you’re trying to do:
That will fail (at execution time) and quite rightly so.
To bring it back to your code, unless
DoSomethingHereactually returns aMyObjectCollectionat execution time, the cast will fail.