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

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?
 
N

Nicholas Paldino [.NET/C# MVP]

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.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top