Question

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)

Was it helpful?

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)]);

OTHER TIPS

You can create from types like this

class MyBase
{
}

class MyClass1 : MyBase
{
}

class MyClass2 : MyBase
{
}

This uses System.Activator to create the object.

void Main()
{
    var typesToPickFrom = new List<Type>()
    {
        typeof(MyBase),
        typeof(MyClass1),
        typeof(MyClass2)
    };

    var rnd = new Random();
    Type typeToCreate = typesToPickFrom [rnd.Next(typesToPickFrom.Count)];
    object newObject = Activator.CreateInstance(typeToCreate);
}

You can cast as needed.

If, as you say, you want to "create" a random instance:

var selection = random.Next(0,2)

switch (selection)
{
    case 1: return new MyBase();
    case 2: return new MyClass1();
    case 3: return new MyClass2();
}

It might be useful to define a common interface for all of these classes, so that you can return something from the method. Or you can simply return an object or a dynamic.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top