0

Here's my code:

void DoSomething<T>()
{
    var constructor = typeof(T).GetConstructor(null);

    if(constructor != null)
    {
        DoSomethingElse<T>(); // compiler error
    }
    else
    {
        //...   
    }

}

void DoSomethingElse<T>() where T:new()
{
   T x = new T();
   //...
}

Is there a way to convince the compiler that T is a legitimate T:new()?

Jonathan Allen
  • 68,373
  • 70
  • 259
  • 447

1 Answers1

4

There is no way to convince compiler other than adding a new() constraint, if you can't do that the only way is to go with Reflection:

var methodType = // get the type of DoSomethingElse here
var genericMethod = methodType.MakeGenericMethod(typeof(T));

// pass instance instead of null if this is an instance method
genericMethod.Invoke(null); 
Selman Genç
  • 100,147
  • 13
  • 119
  • 184