C# Something weird when assigning a class variable

Joined
Jul 13, 2008
Messages
273
Reaction score
147
Hi.

I have the following problem.

Lets say i have this
Code:
class ItemContainer
{
    int itemID {get;set;}
    string Name { get;set;}
    string Description {get;set;}
    // And a lot more things
}
In another file i have a generic list that uses that class
Code:
    class Items
    {
        public static List<ItemContainer> ItemList = new List<ItemContainer>();
    }
In my application i have a button that should copy the selected item to a new item with a new item id

Code:
        private void t_CopyToNew_Click(object sender, EventArgs e)
        {
                        
            int ID = GetIDFromList();

            int i = Items.ItemList.FindIndex(p => p.ItemID.Equals(ID));
            if (i != -1)
            {
                
                ItemContainer newItem = new ItemContainer();
                newItem = Items.ItemList[i];
                
                newItem.Name = newItem.Name + " (Copy)";
                newItem.ItemID = Items.ItemList.Max(p => p.ItemID) + 1;
                newItem.EditFlag = NewItem;

                Items.Menu.Add(newItem.ItemID + " - " + newItem.Name);
                Items.ItemList.Add(newItem);

                MakeList();

                ItemListBox.SelectedItem = newItem.ItemID + " - " + newItem.Name;

            }

           

        }
So, that works, it adds the new record to the gerneric lis.

However..
The moment i do newItem.Name += " (copy)";
It also changes in Items.ItemList and not only in the newItem variable.
Anyone have a idea about why this is happening and what i can do to make newItem have the data of Items.ItemList without it being bound to it ?
 
.NET does not natively support deep cloning, however it can be facilitated by serializing and deserializing objects.


Edit: If strings and value types are all that need to be copied, wrapping Object.MemberwiseClone as a public method should suffice.
 
Last edited:
Back