Connecting Tech Pros Worldwide Help | Site Map

generic generics

Joël
Guest
 
Posts: n/a
#1: Nov 17 '05
Hi!
I want to do something like that :

class Test<T>{
}

string myVar = "System.String";
Type myType = Type.GetType( myVar );
Test<myType> delta = new Test<myType>();

Is it possible to do something like that ?
Thanks for your help

Adam Clauss
Guest
 
Posts: n/a
#2: Nov 17 '05

re: generic generics


"Joël" <Jol@discussions.microsoft.com> wrote in message
news:DC52A8EB-23AD-4281-BBED-1CDED08A8D31@microsoft.com...[color=blue]
> Hi!
> I want to do something like that :
>
> class Test<T>{
> }
>
> string myVar = "System.String";
> Type myType = Type.GetType( myVar );
> Test<myType> delta = new Test<myType>();
>
> Is it possible to do something like that ?
> Thanks for your help[/color]

I don't believe so - if my understanding of generics is correct, they are a
compile time feature. The value of myType cannot be determined until
runtime, so there would be no way to accomplish that.

--
Adam Clauss


Daniel O'Connell [C# MVP]
Guest
 
Posts: n/a
#3: Nov 17 '05

re: generic generics



"Joël" <Jol@discussions.microsoft.com> wrote in message
news:DC52A8EB-23AD-4281-BBED-1CDED08A8D31@microsoft.com...[color=blue]
> Hi!
> I want to do something like that :
>
> class Test<T>{
> }
>
> string myVar = "System.String";
> Type myType = Type.GetType( myVar );
> Test<myType> delta = new Test<myType>();
>
> Is it possible to do something like that ?
> Thanks for your help[/color]

As written, no. You can create generic types via reflection using an
arbitrary type, but I'm not sure what it would buy you. What are you trying
to achieve with this code?

basic generic type construction code(untested, but should work):

string myVar = "System.String";
Type myType = Type.GetType( myVar );
Type testType = typeof(Test<>);
Type genericType = testType.MakeGenericType(new Type[] { myType });

object o = Activator.CreateInstance(genericType);

but you will only get as far as object or antoher base. You cannot treat the
reference as the given generic type due to compile time type checking.


Closed Thread


Similar C# / C Sharp bytes