I was just going through some articles on reflection and generics, and I came across the following code:
public static T CreateControlInstance<T>(FormControl parent)
where T : FormControl
{
T control = GetControlInstance<T>(parent);
//do something with control
}
public static T GetControlInstance<T>(FormControl parent)
{
return (T)Activator.CreateInstance(typeof(T), new object[] { parent });
}
These methods were used like this:
MyButton b = CreateControlInstance<MyButton>(SomeformInstance);
Many controls were created this way. I would just like to know:
Q1. What are the advantages of this approach?
Q2. What are the advantages of this approach, given that the object instance types are known at compile time? (I'm assuming that the button and FormControl
were somehow related to System.Windows.Forms.Control
)
Edit:
I found something similar being done here
Create instance of generic type?
Basically i want to create type(of known type) from strings which got read at runtime?
I wanted to avoid long list of if-then-else in creating objects of specific type depending on the string..but didn't have a clue.
Any one has better solution so that reflection can be avoided to create elements of known type.
End Edit