I’m trying to understand why this cast doesn’t work:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace CastTest {
class Foo {}
// I want to use this kind of like a typedef, to avoid writing List<Foo> everywhere.
class FooList : List<Foo> {}
class Program {
static void Main(string[] args) {
FooList list = (FooList) Program.GetFooList();
}
// Suppose this is some library method, and i don't have control over the return type
static List<Foo> GetFooList() {
return new List<Foo>();
}
}
}
This generates a runtime error:
InvalidCastException: Unable to cast object of type ‘System.Collections.Generic.List`1[CastTest.Foo]’ to type ‘CastTest.FooList’.
Can anyone explain why this doesn’t work, and whether I can get around this somehow?
You cannot automatically cast from a parent class to a derived class: just because the object you’re attempting to cast is a
List<Foo>doesn’t necessarily make it aFooList.Check out:
http://social.msdn.microsoft.com/Forums/is/csharplanguage/thread/f7362ba9-48cd-49eb-9c65-d91355a3daee
You could write an operator that converts a
List<Foo>to aFooList, perhaps usingAddRangeto populate the values, such as:Also, it may be better to just use a
usingalias:http://msdn.microsoft.com/en-us/library/sf0df423(v=vs.80).aspx
This way you’re not actually passing around needless derived classes.