How can I do the following code? I don’t think I understand C # generics completely. Maybe someone can point me in the right direction.
public abstract class A { } public class B : A { } public class C : A { } public static List<C> GetCList() { return new List<C>(); } static void Main(string[] args) { List<A> listA = new List<A>(); listA.Add(new B()); listA.Add(new C());
This is probably the simple answer.
Update: Firstly, this is not possible in C # 3.0, but it is possible in C # 4.0.
To run it in C # 3.0, which is just a workaround until 4.0, use the following:
// Compiler is happy List<A> listB = new List<B>().OfType<A>().ToList(); // Compiler is happy List<A> listC = GetCList().OfType<A>().ToList();
source share