C# Changing Objects within a List

Posted by kwong22 on Stack Overflow See other posts from Stack Overflow or by kwong22
Published on 2010-06-03T01:30:51Z Indexed on 2010/06/03 1:34 UTC
Read the original article Hit count: 223

Filed under:
|
|

Hi, I'm having a little problem changing members of an object in a list using a found index.

So this is the method I am currently working with:

        static void addToInventory(ref List<baseItem> myArray, baseItem item, float maxAmount, ref float currentAmount)
    {
        if (currentAmount + item.getWeight() <= maxAmount)
        {
            Console.WriteLine("item.Quantity = {0}", item.Quantity);
            if (myArray.Contains(item))
            {
                Console.WriteLine("Item ({0}) already exists", item.Name);
                int id = myArray.IndexOf(item);
                myArray[id].Quantity += item.Quantity;//Change occurs in this line, item.Quantity becomes the same as myArray[id].Quantity
            }
            else
            {
                Console.WriteLine("Adding new item ({0})", item.Name);
                myArray.Add(item);
            }
            currentAmount += item.getWeight();
        }
        else
        {
            Console.WriteLine("Inventory full");
        }
        myArray.Sort();
    }

This method takes several parameters including the inventory/list. I check if the item fits in and if it does, I see if there is another item of the same name in the list, find the index, and add more of the item. However, the quantity of the item added suddenly becomes the same as the quantity of the item in the list. For some reason, this also changes the quantity of the item outside of the list. So therefore, instead of quantities adding up like this: 1, 2, 3, 4, they add up like this: 1, 2, 4, 8.

I've just started to learn how to use lists so if there is anything I'm missing, don't hesitate to criticize. Thanks in advance.

© Stack Overflow or respective owner

Related posts about c#

Related posts about list