'identifier': cannot provide arguments when creating an instance of a variable type

  • Thread starter Thread starter tbandrow
  • Start date Start date
T

tbandrow

I would like to get this to compile:

public class GenericCtor<T> where T: class, new()
{
public static T MakeIt()
{
return new T(1, 2);
}
}

public class GenericCtorItem
{
int A, B;

public GenericCtorItem(int a, int b)
{
A = a;
B = b;
}
}

The documentation says: "This error occurs if a call to the new
operator on a type parameter has arguments. The only constructor that
can be called using the new operator on an unknown parameter type is a
constructor with no arguments. If you need to call another constructor,
consider using a class type constraint or interface constraint."

Which to me, implies that if use a class type or interface constraint,
this should work:

public class GenericCtor<T> where T: GenericCtorItem, new()
{
public static T MakeIt()
{
return new T(1, 2);
}
}

public class GenericCtorItem
{
int A, B;

public GenericCtorItem(int a, int b)
{
A = a;
B = b;
}
}

But, it doesn't. Is there a way at all to call a constructor for this?
 
No, there isn't a way to do this. Constraints on an interface don't
matter, since interfaces can't have constructors. With class constraints,
any derived class can be used for T as well, and derived classes do not
inherit constructors.

Hope this helps.
 
Back
Top