-
Assuming
class A
{ }class B : A
{ }
covariance is not supported for generic class.
Meaning – we cant do something like this :
MyConverter<B> x1= new MyConverter<B>();
MyConverter<A> x2= x1;
Thats fine and understood.
From my reading – i understand that Covariance will be available:
“If you use a backing Generic Interface Being implemented on a Generic Class – so that access to the T type object instance will be available through those interfaces “.
I have just one problem.
Ive seen many examples of the “converter” class as a form of Stack .
But never understood ” what if I want to use only 1 instance of B from a reference of A ? “
so Ive tried some code :
Create
Bobject + values —> use Generic Converter forB—>
use the covariance flow to get itsAreference —> now you can use it
either as A or as B.


My question :
Is That the correct way of doing this ( for using covariance for 1 object only ) ?
p.s.
The code is working and compiled ok. https://i.stack.imgur.com/PJ6QO.png
Ive been asking /reading a lot about this topic lately – I dive into things in order to understand them the best I can.
Your code compiles and works, so is it “correct”? I guess it is!
However it is not very interesting having a stack that only contains a single element; that’s not really a stack. Let’s think about how you might make a truly covariant and contravariant stack.
And now you can use the stack covariantly for popping, and contravariantly for pushing:
Your question is “what if I want to use a Tiger but I have a reference an Animal?” The answer is “you can’t” because the Animal might not be a Tiger! If you want to test whether the reference to Animal is really a tiger then say:
or
That’s not possible. There is no reference conversion there. The only covariant and contravariant reference conversions in C# 4 are on generic interfaces and generic delegates that are constructed with reference types as the type arguments. Generic classes and structs may not be used covariantly or contravariantly. The best thing you can do is make the class implement a variant interface.