I want a magic to happen like that…
class SomeClass {}
public static void main()
MagicFunctionOrMacrosOrSomethingThatGetTypeOf("SomeClass") some_var = null;<br />
}
Maybe it’s crazy, but is it possible?
I need it to avoid crazy large switch case, because has a lot of classes, but at certain point of code is unable to tell what of the classes to create.
Let’s have an example:
I have base class:
class baseCLASS {}
have a lot of child classes:
class class1 : baseCLASS {}
class class2 : baseCLASS {}
…
class classn : baseCLASS {}
have some flag that comes from outside to events handler:
string class_name; //actually i use int flag that should have connected with string names in dictionary.
have forced to make this:
switch(class_name)
case "class1":
class1 some_class = new class1();
some_class.RunHandler();
break;
case "class2":
class2 some_class = new class2();
some_class.RunHandler();
break;
case "classn":
classn some_class = new classn();
some_class.RunHandler();
break;
}
I want to replace that large switch statement by something like this:
MagicFunctionOrMacrosOrSomethingThatGetTypeOf(class_name) some_var = null;
... some initialization actions with some_var
some_var.Build();
some_var.RunHandler();
oh my…
You have two problems:
Dictionary<string,type>, and populate it; or you can attach an attribute to each class, showing which “verb” it handles. Once you’ve done that, you can useActivator.CreateInstanceto (at runtime) create an instance of your unknown class. This returnsobject.IRunnableor something), or usedynamic, which gives you duck typing.