By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
455,467 Members | 1,619 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 455,467 IT Pros & Developers. It's quick & easy.

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

P: n/a
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?

Apr 5 '06 #1
Share this Question
Share on Google+
1 Reply


P: n/a
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.
--
- Nicholas Paldino [.NET/C# MVP]
- mv*@spam.guard.caspershouse.com

<tb******@storkyak.com> wrote in message
news:11**********************@e56g2000cwe.googlegr oups.com...
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?

Apr 5 '06 #2

This discussion thread is closed

Replies have been disabled for this discussion.