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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With