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.)
new(int, int, bool, int, bool)-- it may meet the form of one of your constructors, but good luck figuring out what that constructor's supposed to do.)new()constraint and to use the default constructor(add it). Then use theIndexproperty:public static T validate<T>(int index) where T : A, new() { if (validation) return null; T t = new T(); t.Index = index; return t; }Otherwise you could useActivator.CreateInstancelike here