I need to create Dynamic T using interface. But I am getting "Type Casting" error. Here is my code :
interface IEditor { }
class Editor : IEditor { }
class Test<T> { }
Now the will be dynamic so I am using this code below :
Test<IEditor> lstTest = (Test<IEditor>)Activator.CreateInstance(typeof(Test<>).MakeGenericType(typeof(Editor)));
I am getting following error
Unable to cast object of type 'CSharp_T.Test`1[CSharp_T.Editor]' to type 'CSharp_T.Test`1[CSharp_T.IEditor]'.
This error is not compilation error but I am getting run time error.
Generic classes do not support covariance, but interfaces do. If you define an interface ITest<> and mark T as an out parameter, like this,
interface IEditor { }
class Editor : IEditor { }
interface ITest<out T> { }
class Test<T> : ITest<T> { }
you will be able to do this:
ITest<IEditor> lstTest = (ITest<IEditor>)Activator
.CreateInstance(typeof(Test<>)
.MakeGenericType(typeof(Editor)));
However, this would limit the ways in which the T parameter could be used inside ITest<> and its implementations.
Demo on ideone.
Test is not covariant (it is invariant in it's generic argument). Because of this a Test<IEditor> is not a subtype of a Test<IEditor>. There is no relationship between those two types.
You can create an object of type Test<IEditor> to begin with, instead of a Test<IEditor>, and then the cast can succeed.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With