With listbox.Items.Add(s);
you are adding only one item being the array itself. Use AddRange
instead to add the elements of the array.
listbox.Items.AddRange(s);
Another way to make it work is to set the DataSource
:
listbox.DataSource = s;
Let's see what happens in your codeh in detail (with line numbers)
1 String[] s = new string[] { "5", "2", "3" };
2 listbox.Items.Add(s);
3 s[2] = "0";
4 listbox.Items.Add(s);
- An array is created and initialized.
- This array is added as one single item to the ListBox. Note that the array is a reference type. So indeed, you are only adding a reference to the ListBox, not a copy of the array.
- One element of the array is changed. This affects the first item added to the ListBox as well, since it contains a reference to this unique array.
- The same array-reference is added as an item to the ListBox. Now the ListBox contains 2 items referencing the same array with the same elements.
If you want the items to contain 2 distinct arrays, you can clone the array:
string[] s = new string[] { "5", "2", "3" };
listbox.Items.Add(s);
var s2 = (string[])s.Clone();
s2[2] = "0";
listbox.Items.Add(s2);
Now you have two distinct items in the ListBox. Note that the Array.Clone Method creates a shallow clone. I.e. the array elements themselves are not cloned. So, if they are reference types, both arrays will contain the same objects just after cloning. But since you have 2 distinct arrays, you can replace elements of an array without affecting the other array.
You can add a clone method to your own classes
public class MyOwnClass
{
public string Prop1 { get; set; }
public int Prop2 { get; set; }
public MyOwnClass ShallowClone()
{
return (MyOwnClass)MemberwiseClone();
}
}
MemberwiseClone
is inherited from System.Object
.