Reputation: 15
I am in need of assistance, since I am stuck on a problem I have encountered. I have a List, List<Items> ItemList
and I want to put some ContainerItems into that list, but when I do, all of the ContainerItems properties are gone and it turns into the baseclass of Items
class Items
{
public Items()
{
}
public string Name { get; set; }
public int durability { get; set; }
}
class ContainerItems : Item
{
public ContainersItem()
{
}
public int maxItems { get; set; }
public List<Items> ContainItems { get; set;}
}
Ideally I would like store all of the Items I'm making into a Dictionary<string,Items>
. Is there anyway to store all the Items and ContainerItems together and keep their properties? thanks in advance!
Upvotes: 1
Views: 56
Reputation: 781
You will have either (1) define your list as List<ContainersItem>
or (2) cast the content of your list in ContainersItem
each time you want to use fields or functions specific to this class
Upvotes: 1
Reputation: 119017
Lets say you have your list of Items:
public List<Items> ContainItems { get; set }
And now you want to loop through them, but safely as not all of the members of the list will be a ContainerItems
object:
foreach(var item in ContainItems)
{
if(item is ContainerItems)
{
var containerItems = (ContainerItems)item;
}
else
{
//Otherwise deal with it as an Items object
}
}
Upvotes: 2