Accessing the children attributes in a list of parent-type class

  • Thread starter Thread starter Commmme
  • Start date Start date
C

Commmme

Guest
I created a first class with its attributes

public class Item
{
public int quantity;
public string type;
}

then, I created children classes like

public class Apple : Item
{
public string taste;
public int price;
}

public class Banana : Item
{
public bool rotten;
public int size;
}

To create a list of Item I used

List<Item> m_items = new List<Item>();

It works if I want to add a Banana or an Apple but I can only acces the Item attributes, i.e.

// (considering the first item to be a Banana)
m_items[0].quantity // works
m_items[0].rotten // doesn't work


Now I understand that my list is a list of Item so I will only be able to access the Item attributes, but my question is how could I create a list that allows me to access the children attributes? I search the internet and found things about generic lists but there must be an easier way.


Come

Continue reading...
 
Back
Top