Home All Groups Group Topic Archive Search About

creating instances of generic types

Author
17 Mar 2006 6:06 PM
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.

Author
17 Mar 2006 6:20 PM
Yury
public class SomeClass<T, K>
    where T : new()
    where K : new()
{
    T t;
    K k;

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

Bookmark and Share