views:

63

answers:

2

Hello,

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

+2  A: 

Probably it looked similar to this:

public static Create<T>() where T : new()
{
    return Activator.CreateInstance(typeof(T));
}

Some explanations:

  • Activator.CreateInstance(typeof(T)) creates an object of type T. You could optionally pass parameters to the constructor being called (check the reference documentation for a parameter overview for Activator.CreateInstance), but since this should work for almost any T, providing constructor arguments is too specific and not a good idea.

  • That's why where T : new() is needed. This puts a new() constraint on type parameter T. What this means is that this method is only valid for types T that provide a parameter-less ("default") constructor.


P.S.: Note that you only need Activator.CreateInstance when all you have to work on is a System.Type. In the above example, you actually have a type name T, so new T() would be preferable. See @Guffa's answer for this.

stakx
you can also use Activator.CreateInstance<T>()
Sergey Mirvoda
Thanks! That's the one! :D I think my memory got temporarily deaded, lol.
lucifer
+2  A: 

You can specify a condition for the generic type. If you specify that it has to have a constructor, you don't even need Activator to call it:

public static Create<T>() where T : new() {
  return new T();
}

If you want to use parameters in the constructor call, you would use the Activator, but then the condition that the class should have a parameterless constructor is pointless.

Guffa
Thank you for your answer. :)
lucifer