Home All Groups Group Topic Archive Search About
Author
9 Apr 2007 5:52 PM
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.

Author
9 Apr 2007 6:07 PM
Jon Skeet [C# MVP]
Enosh Chang <changen***@yahoo.com.tw> wrote:
Show quote
> 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.

--
Jon Skeet - <sk***@pobox.com>
http://www.pobox.com/~skeet   Blog: http://www.msmvps.com/jon.skeet
If replying to the group, please do not mail me too

AddThis Social Bookmark Button