I can’t seem to find out how to do this in .NET2.0 despite searching Google and SO.
Say I have the following classes:
public class Fruit {
prop string Color {get; set;}
}
public class Apple : Fruit {
public Apple() {
this.Color = "Red";
}
}
public class Grape: Fruit {
public Grape() {
this.Color = "Green";
}
}
Now I want to do this:
public List<Fruit> GetFruit() {
List<Fruit> list = new List<Fruit>();
// .. populate list ..
return list;
}
List<Grape> grapes = GetFruit();
But of course I get Cannot implicitly convert type Fruit to Grape.
I realize this is because I could really mess things up if I did:
List<Grape> list = new List<Grape>();
list.add(new Apple());
Because while both are Fruit, an Apple isn’t a Grape. So that makes sense.
But I don’t understand why I can’t do this:
List<Fruit> list = new List<Fruit>();
list.add(new Apple());
list.add(new Grape());
At the very least, I need to be able to:
List<Fruit> list = new List<Fruit>();
list.add(new Apple()); // will always be Apple
list.add(new Apple()); // will always be Apple
list.add(new Apple()); // will always be Apple
Any ideas on how to do this in .NET2?
Thanks
EDIT
Sorry, I was mistaken. I can in fact do:
List<Fruit> list = new List<Fruit>();
list.add(new Apple());
list.add(new Grape());
The .FindAll and .Convert did the trick.
Since you need something specific in
.Net 2.0first I would filter each using FindAll then use ConvertAll.As for your questions:
You can do this, it is completely valid, did you mistype something (add vs Add)?