Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Create Dynamic <T> in C#

Tags:

c#

c#-4.0

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.

like image 784
Debajit Mukhopadhyay Avatar asked Jan 26 '26 13:01

Debajit Mukhopadhyay


2 Answers

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.

like image 79
Sergey Kalinichenko Avatar answered Jan 29 '26 02:01

Sergey Kalinichenko


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.

like image 22
Servy Avatar answered Jan 29 '26 01:01

Servy



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!