Initialize generic type with non-empty constructor

Viewed 5605

Referencing to that Question: Cannot create an instance of the variable type 'Item' because it does not have the new() constraint

I would like to create an instance from a generic type with a non empty constructor.

public class A{};

public class B
{
   public B(int){/*...*/}
}

public class C
{
   public static T validate<T>(int index) 
      where T : A, 
      new(int) //error
   {
      if(/*validation*/)
         return null;
      return new T(index);
   }
}

If I try to call B b = validate<B>(42); I got this error:

'B' must be a non-abstract type with a public parameterless constructor in order to use it as parameter 'T' in the generic type or method 'C.validate(int)'

Question 1: Why can I use a parameterless constructors only?

Question 2: How can I solve my problem without delegates or interfaces? (I am always looking for fancy solutions.)

3 Answers
Related