Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

convert generic type to base class

Tags:

c#

generics

public class Base {...}

public class Complex: Base {...}

public class MyOtherClass<T> {...}

and a list of the two type

List<MyOtherClass<Complex>> listOfComplex
List<MyOtherClass<Base>> listOfBase

I want have a list

listOfComplex.Union(listOfBase)

but i cant convert generic of a type to a generic of another type even if Complex derive fro Base It's possibble to have a list of a base class?

like image 789
user3401335 Avatar asked Jul 28 '26 00:07

user3401335


1 Answers

Although Complex derives from Base, there is no such relationship between MyOtherClass<Complex> and MyOtherClass<Base>. That is the reason why you cannot create an Union of the two lists. For the framework both generic types are completely different.

The solution now really depends on what exactly your class does. Check out the topic of covariance and contravariance here in Docs - these are two special cases in which you will be permitted to create conversions between the two generic types if the types either are input or output only.

You could also add custom cast or manually cast the items to the "base" type before doing the "union" operation.

like image 53
Martin Zikmund Avatar answered Jul 30 '26 19:07

Martin Zikmund



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!