Say, we have a generic class like this:
public sealed class Class1<T>
{
private T _value;
public T Value
{
get { return _value; }
}
}
I want to initiate an object of type Class1
but type argument T
is only dynamically available using GetType()
. Is that possible to use a generic class with dynamic type as follows?
Class1<anObject.GetType()> obj = new Class1<anObject.GetType()>();
I know this code even can not be compiled but I need some sort of generic usage like this.
According to this answer I should use MakeGenericType
to infer the T argument using the reflection and create the object as follows:
Type typeArgument = anObject.GetType();
Type genericClass = typeof(Class1<>);
Type constructedClass = genericClass.MakeGenericType(typeArgument);
object created = Activator.CreateInstance(constructedClass);
But I don't know how to use object created, later! Because this is an implicit object and do not have access to its property Value. I also can't cast it to the Class1
, If I could I didn't have to use MakeGenericType
at first! How could I access the Value after I created the object ?