I got a class X and a class Y, the latter which derives from X :
class x {}
class y : x {}
Then somewhere I am using a list of X :
List<X> lstX;
...
Then I’d like to use a new list of Y, from the data in my other list…something along those lines :
List<Y> lstY = lstX;
I would believe that the items in the list of X would get converted automatically into Y, but thats not the case.
Also, how could I initialize a new instance of Y, from a certain X? I would like to do :
var newX = new X();
var newY = new Y(X);
but it does not seem to work like that.
Thanks for your help!
and sorry for formatting, trying my best
There are a couple of questions here.
First: “I can assign an object of type Tiger to a variable of type Animal. Why can I not assign an object of type List of Tiger to a variable of type List of Animal?”
Because then this happens:
In C# 4 it will be legal to do this:
This is legal because
IEnumerable<T>has no “Add” method and therefore this is guaranteed to be safe.See my series of articles on covariance for details about this new feature of C# 4.
http://blogs.msdn.com/ericlippert/archive/tags/Covariance+and+Contravariance/default.aspx
Second question: “how could I initialize a new instance of Tiger, from a certain Animal?”
You cannot. The Animal in question could be a Ladybug. How are you going to initialize a new Tiger from an instance of Ladybug? That doesn’t make any sense, so we don’t let you do it. If you want to write your own special method that knows how to turn arbitrary animals into tigers, you are free to do so. But we don’t know how to do that for you.