0

I have a generic type who's gotten a function that creates an instance of the parameter type. When creating the parameter type, is there a way to use a constructor that takes arguments?

class MyGenericClass<T>
{
  public T Create()
  {
    return new T("created by MyGenericClass");
  }
}

Are there any constraints I can place on the type that qualifies it to be constructed with a parameter?

EDIT: My actual need is to use the parameter type as follows:

    class MyGenericClass<T>
    {
      public T SomeFunction()
      {
        using (var t = new T("created by MyGenericClass"))
        {
          // actions with t
        }
      }
    }
Social Developer
  • 405
  • 5
  • 16
  • In short - NO... – Backs Sep 27 '17 at 15:01
  • 2
    Nope - not at the moment. – Jon Skeet Sep 27 '17 at 15:01
  • be careful, the parameter less `new T()` uses reflection, so while it looks cute on syntax, its monster when compiled. Microsoft should really optimize `new()` constraint and also add support for parameters. https://stackoverflow.com/questions/367577/why-does-the-c-sharp-compiler-emit-activator-createinstance-when-calling-new-in – M.kazem Akhgary Sep 27 '17 at 15:07

0 Answers0