Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I create a Dictionary of classes, so that I can use a key to determine which new class I want to initialize?

As per the question, how do I create a Dictionary in C# where the key is say, an integer, but the values are classes that I can call the constructor for by using just the value in the Dictionary? Each of the classes are derived from an abstract class, and they take the same parameters, so I feel like I should be able to store the resulting reference to the new class object in a variable of the abstract class type.

That being said, a Dictionary's value set is usually filled with references to objects, not types themselves. As a quick example, here's what I'm trying to do:

abstract class BaseObject {

     int someInt;
}

class ObjectA : BaseObject {

    ObjectA (int number) {
        someInt = number;
    }
} 

class ObjectB : BaseObject {

    ObjectB (int number) {
        someInt = number;
    }
}

And I want to be able to do the following:

Dictionary<int, ???????> objectTypes = new Dictionary<int, ???????>();

objectTypes.Add(0, ObjectA);
objectTypes.Add(1, ObjectB);

So I can eventually:

BaseObject newObjectA, newObjectB;

newObjectA = new objectTypes[0](1000);
newObjectB = new objectTypes[1](2000);

The syntax is probably quite different, but I hope I at least got across what I'm trying to accomplish.

like image 608
Kyton Avatar asked Nov 30 '25 06:11

Kyton


1 Answers

Are you looking for something like this?

var objectTypes = new Dictionary<int, Func<int, BaseObject>>();
objectTypes[0] = input => new ObjectA(input);
objectTypes[1] = input => new ObjectB(input);

objectTypes[0](1000);
objectTypes[1](2000);

Here instead of storing object, I store a Func to generate each concrete object

like image 128
Phuong Nguyen Avatar answered Dec 01 '25 20:12

Phuong Nguyen