Re: Getting the Type of a Generic Parameter



Hello Rick!

The problem is that I don't actually need create a type from the
generic parameter, but need to instantiate the type specified BY the
parameter. The generic parameter is an object and I need to
instantiate that type. IOW, it's not - for example - List<T> that I
need to instantiate but T itself.
In essence what I need to do is:

Activator.CreateInstance<T>();

with the added requirement of passing constructor parameters.

You just have to use a typeof(T) in order to call the CTOR or to use
Activator:

class C<T> where T:Something{

void foo() {
Type t = typeof(T);
ConstructorInfo ctor = t.GetConstructor(
new Type[]{typeof(int), typeof(string)}
);

if(ctor == null)
throw new ArgumentException("T is invalid, because no CTOR(int,
string) is available!");

Something instance = (Something)ctor.Invoke(new object[]{1,
"hello"});

// do whatever you want
}

}


OK?



GP


.



Relevant Pages

  • Re: Getting the Type of a Generic Parameter
    ... The problem is that I don't actually need create a type from the generic parameter, but need to instantiate the type specified BY the parameter. ... with the added requirement of passing constructor parameters. ... You have to construct the concrete Type before calling Activator.CreateInstance. ...
    (microsoft.public.dotnet.framework.clr)
  • Re: Is it possible to achieve this?
    ... through the generic parameter. ... but defined at compile time: ... For example, not only how you want to instantiate this class, but also where you are concerned about the implementation being exposed, and why. ... <Long English sentences between angle brackets> ...
    (comp.lang.java.programmer)

Loading