Reputation: 2179
I have some code that searches for all types of type MyType<T>
in an assembly. T
can be any type I use Activator.CreateInstance
to create objects of these types. I need to pass these objects into a method that is expecting MyType<T>
so I need to somehow cast each object from Object (returned by Activator.CreateInstance
) to something of MyType<T>
.
Upvotes: 1
Views: 753
Reputation: 9417
what you need is a combination of GetGenericTypeDefinition - MakeGenericType combination to form your own new type. here is an example:
public class GenericTypeTest<T>
{
T value;
}
void MakeTest()
{
var newType = typeof(double);
var customType = typeof(GenericTypeTest<object>).GetGenericTypeDefinition().MakeGenericType(newType);
var createdObject = Activator.CreateInstance(customType);
}
if you want to use that createdObject, it is a little complicated because you can't "hard code" anything:
public class GenericTypeTest<T>
{
public GenericTypeTest(T value)
{
this.value = value;
}
public T value {get; protected set; }
}
public void ShowSomething<T>(GenericTypeTest<T> genericContainer)
{
MessageBox.Show(genericContainer.value.ToString());
}
void MakeTest()
{
var newType = typeof(double); object newValue = 1.0;
var customType = typeof(GenericTypeTest<object>).GetGenericTypeDefinition().MakeGenericType(newType);
var createdObject = Activator.CreateInstance(customType, newValue);
this.GetType().GetMethod("ShowSomething").MakeGenericMethod(newType).Invoke(this, new object[] { createdObject });
}
Upvotes: 1