Generic question

E

Enosh Chang

Hi all:

I have one question about generic class.

public class Base<T>
where T : new()
{
public Base() {}

public void A()
{
T newObject = new T(parameter);
}
}

Document said I couldn't use T(parameter) but T(). Or do I have another way to do that? Thanks.
 
J

Jon Skeet [C# MVP]

Enosh Chang said:
Hi all:

I have one question about generic class.

public class Base<T>
where T : new()
{
public Base() {}

public void A()
{
T newObject = new T(parameter);
}
}

Document said I couldn't use T(parameter) but T(). Or do I have
another way to do that? Thanks.

You'd have to use reflection, which bypasses some of the benefits of
generics. You can't specify that a generic type has to have a
particular constructor signature other than a parameterless
constructor.
 

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