How to define a "List" of derived classes?

c#, class, derived, types

Solution

Something like (assuming a no-args constructor and that B and C are derived from A):

List<Type> types = new List<Type> { typeof(A), typeof(B), typeof(C) };

A instance = (A)Activator.CreateInstance(types[r.Next(0, types.Count)]);

Problem

I have a base class and some derived classes ``` public class MyBase {...} public class MyClass1 : MyBase {...} public class MyClass2 : MyBase {...} ``` Now I want to make a list of these derived classes (classes!! Not instances of classes!), and then I want to create one instance of one of these derived class randomly. How does this work?? Here what I want in pseudo C# :) ``` List<MyBase> classList = new List<MyBase> () { MyClass1, MyClass2, MyClass3, ...} MyBase randomInstance = new classList[random.Next(0,classList.Count-1)](); ``` (unfortunately this List construction expects instances of MyBase but not class names)

Original source