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
this return line will always throw an InvalidCastException. As Lee already commented, classes are invariant. This means that for example MyClass and MyClass 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.