Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to define a "List" of derived classes?

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)

like image 691
CSharper Avatar asked Dec 18 '25 19:12

CSharper


2 Answers

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)]);
like image 57
nitzmahone Avatar answered Dec 20 '25 08:12

nitzmahone


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.

like image 32
Christopher Stevenson Avatar answered Dec 20 '25 09:12

Christopher Stevenson



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!