I have a generic class as shown below
public class MyClass
{
public T MyProp { get; set; }
}
Now I want to return the instance of
What you are trying to do is not possible. While you can create a generic type for an arbitrary generic type argument at runtime like this
public MyClass<object> ReturnWithDynamicParameterType(Type genericArgument)
{
Type genericType = typeof(MyClass<>).MakeGenericType(genericArgument);
return (MyClass<object>)Activator.CreateInstance(genericType);
}
this return
line will always throw an InvalidCastException
. As Lee already commented, classes are invariant. This means that for example MyClass<object>
and MyClass<string>
are simply not the same types. They are not even inherited from one another.
Even co-variance won't help since the out
keyword is not allowed for generic parameters in classes.
I don't see a solution for this without knowing the types at compile-time. But I'm sure that you can solve what you are actually trying to achieve by other methods.
I am not sure if this fits your use, but your only way out is the use of an interface that is covariant.
public interface IMyClass<out T>
{
T MyProp { get; }
}
public class MyClass<T> : IMyClass<T>
{
public T MyProp { get; set; }
}
public IMyClass<object> ReturnWithDynamicParameterType()
{
//This function determines the type of T at runtime and should return instance of MyClass<T>
return new MyClass<string>();
}
This code compiles because your return type is not a class, but a covariant interface (note the out T
on the type parameter). That interface allows retrieval only, so the get;set
on the property has been replaced by a get on the interface.