I am trying to generate an instance of a subclass depending on the given input, so I have created a dictionary that takes a System.Type as a key (although I will create an example using a string for easier understanding) and returns a System.Type as a value.
Something like this:
Dictionary<string, System.Type> types = new Dictionary<string, System.Type>()
{
{ "Weapon", System.Type.GetType("WeaponClass") },
{ "Consumable", System.Type.GetType("ConsumableClass") },
{ "Resource", System.Type.GetType("ResourceClass") }
};
WeaponClass
, ConsumableClass
and ResourceClass
are subclasses of the same class, ItemClass
.
So I would like to create a function that does something like this:
public ItemClass CreateItem(string itemName)
{
System.Type type = types[itemName];
// This is the part that I don't know how to make
return new type();
}
This should return an instance of the corresponding subclass, but I don't know how to do it.
Can anyone help me out?