In my C # code, I came across some interesting covariance problem.
I have a common Matrix<T> class, and it was created, for example, Matrix<int> , Matrix<object> and Matrix<Apple> .
For my business logic, I wrapped them in a generic Wrapper<T> . This Wrapper does not implement the common INonGenericWrapper interface. So I have a Wrapper<int> , Wrapper<object> and Wrapper<Apple> .
My problem: I would like to define a container for all these 3 Wrapper s. I cannot say List<Wrapper<object>> because I cannot insert a Wrapper<int> into this collection. I canβt even tell List<INonGenericWrapper> , because inside my foreach I would like to access the general Matrix<T> parameter.
Cheese: these Wrappers will be (de-) serialized with a specific type: MySerializer<Wrapper<Apple>>.Serialize(_myInstanceOfWrappedApple) .
I think it is clear that I would like to avoid the huge typeof switches when serializing ..
What are my possible workarounds? I'm a little stuck.
Thanks in advance,
source share