Creating T From Type

  • Thread starter Thread starter sternr
  • Start date Start date
S

sternr

Hey,
I have the following class:

public Child<T>
{
//Some Code
}

Can I (using Reflection or any other way) create a Child object in
runtime without knowing what is T? like this:
static object GetChild(Type t)
{

}

Thanks ahead

--sternr
 
Hey,
I have the following class:

public Child<T>
{
//Some Code

}

Can I (using Reflection or any other way) create a Child object in
runtime without knowing what is T? like this:
static object GetChild(Type t)
{

}

I think you'll have to use
static object GetChild<T>() : where T : new()
 
Hello sternr,

[TestFixture]
public class Tests {
[Test]
public void Test( ) {
Assert.AreEqual(typeof(MyClass<string>),
CreateTypeForType(typeof(string)).GetType());
}

private object CreateTypeForType(Type genericParameter) {
Type openType = typeof(MyClass<>);
Type finalType = openType.MakeGenericType(genericParameter);
return Activator.CreateInstance(finalType);
}
}

public class MyClass<T> {
}


Oliver Sturm
 
Hello sternr,

[TestFixture]
public class Tests {
[Test]
public void Test( ) {
Assert.AreEqual(typeof(MyClass<string>),
CreateTypeForType(typeof(string)).GetType());
}

private object CreateTypeForType(Type genericParameter) {
Type openType = typeof(MyClass<>);
Type finalType = openType.MakeGenericType(genericParameter);
return Activator.CreateInstance(finalType);
}
}

public class MyClass<T> {
}

Oliver Sturm
--http://www.sturmnet.org/blog

Brilliant piece of code!
Thanks a lot Oliver!!!

--sternr
 

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

Back
Top