creating instances of generic types


S

Scott Walters

What I want to do is this...

public class c1 <T1, T2> where T1 : new()
{
private T1 at1;
private T2 at2;

public c1()
{
at1 = new T1();
at2 = new T2();
}
}

but I can't make the new() constraint work for more than one class.

So I tried this...

public class c1 <T1, T2> where T1 : new()
{
private T1 at1;
private T2 at2;

public c1()
{
at1 = new T1();
}

private T2 CreateTheT2<T2>() where T2 : new()
{
at2 = new T2();
}
}

with the intention of calling CreateTheT2 later but it gives me the
"cannot implicitly convert type" compiler error. I guess it thinks the
T2 from the class declaration is different from the T2 from the method.

How can I create instaces of both of these generic types from this class?

Thanks.
 
Ad

Advertisements

Y

Yury

public class SomeClass<T, K>
where T : new()
where K : new()
{
T t;
K k;

public SomeClass()
{
t = new T();
k = new K();
}
}
 

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