I’m sorry, but a while ago I wrote a piece of code that was so nice. And now I’m trying to remember it for a new project.
All I can remember about it is that it looked something like this:
public static Create<T>() *something missing here* : *Something missing here*
{
// add methods etc here. I also think I remember something like " Activator.CreateInstance" being used. But I'm not sure.
}
Has anybody written code like this before? Basically what it did was it created a control and passed it back to another project.
Thank you
jt
Probably it looked similar to this:
Some explanations:
Activator.CreateInstance(typeof(T))creates an object of typeT. You could optionally pass parameters to the constructor being called (check the reference documentation for a parameter overview forActivator.CreateInstance), but since this should work for almost anyT, providing constructor arguments is too specific and not a good idea.That’s why
where T : new()is needed. This puts anew()constraint on type parameterT. What this means is that this method is only valid for typesTthat provide a parameter-less (“default”) constructor.P.S.: Note that you only need
Activator.CreateInstancewhen all you have to work on is aSystem.Type. In the above example, you actually have a type nameT, sonew T()would be preferable. See @Guffa’s answer for this.