blah blah blah is here! blah blah » Close

up0down
link

Classes:
class Item
class Inventory : List<Item>
class Bandage : Item
Methods:
class Inventory : List<Item> has this method to add items:
public void AddItem(Item e, List<Item> list)
{
if (list.Contains(e))
e.amount++;
else
list.Add(e);
}
Functions:
player.inventory.AddItem(bandage, player.inventory);
Maybe I'm wrong, and being that this is my first time using Generics I could be, but shouldn't this:
1. look in list for 'e' and increment e by 1 if e already exists in list?
2. add e to the list if it doesn't exist?
upon first run, there are no bandages in player.inventory, so it adds 'e'.
upon second run, it adds 'e' to the list again.
why isn't it seeing that 'e' is already part of the list?

last answered 2 years ago

1 answers

up0down
link

OK fixed it with:
public void AddItem(Item e, List<Item> list)
{
if (Count > 0)
{
for (int i = 0; i < Count; i++)
{
if (list.Contains(this[i]))
this[i].amount++;
else
list.Add(e);
}
}
else
list.Add(e);
}

This post was imported from csharpfriends, if you have a similiar question please ask it again.

All previous members have been migrated, hope you enjoy the new platform!

Feedback