2

In the code below, a reference type is being added. How can i do this value type?

 imgList.Items.Add(imgList.Items[0]);

    imgList.Items[imgIndex].Data = input; <== **This updates the 0th and the newly added element which is the issues**

Please advise

Shamim Hafiz - MSFT
  • 21,454
  • 43
  • 116
  • 176
Amit
  • 6,839
  • 21
  • 56
  • 90

1 Answers1

2

In order to avoid this issue, you need to clone imgList.Items[0] before adding it to imgList.Items. This basically involves creating a new object of the same type and populating it with data from the original.

The complexity of doing so depends on what the object is, but look at the answers to this question for some tips on cloning objects.

Edit: I forgot that .MemberwiseClone was protected.

You don't say in your code what the type of object is that you're adding to the list. If it's a class of yours, you can add a method to return a copy:

public MyType ShallowCopy()
{
    return (MyType)this.MemberwiseClone();
}

and use

imgList.Items.Add(imgList.Items[0].ShallowCopy());

Or you can add a copy constructor:

public MyType(MyType original)
{
    // Copy each of the properties from original
    this.Data = original.Data;
}

and use

imgList.Items.Add(new MyType(imgList.Items[0]));
Community
  • 1
  • 1
Steve Morgan
  • 12,978
  • 2
  • 40
  • 49