Paulj
Paulj

Reputation: 3194

ASP.net c# magical array issue

I'm encountering an interesting issue with the following code. productObject is a custom object that contains a number of product-related variables including a 'VendorLocationId'.

Given these items in a listbox:

"Town A" value:1

"Town B" value:2

Also given: both items are selected within the listbox.

1  productObjectArray[] productObjectArray = new productObjectArray[lstLocation.Items.Count];
2  int counter = 0;
3  foreach (ListItem li in lstLocation.Items)
4  {
5    if (li.Selected == true)
6    {
7      productObject.VendorLocationId = li.Value;
8      productObjectArray[counter] = productObject;
9    }
10   counter++;
11 }

After executing, the above code gives this result:

productObjectArray[0].VendorLocationId = 2
productObjectArray[1].VendorLocationId = 2 

I find this perplexing. If I step through the code, productObjectArray[0].VendorLocationId = 1 and counter = 1 until line 7. Then productObjectArray[0].VendorLocationId magically equals 2 and counter = 1.

Upvotes: 1

Views: 251

Answers (2)

DocMax
DocMax

Reputation: 12164

It looks like you are using a single instance of productObject and setting the two items in productObjectArray to both point to that single instance. VendorLocationId is 2 in both because that was the last value set to productObject.

Upvotes: 1

BFree
BFree

Reputation: 103740

It seems that your "productObject" is declared outside of this code block, and you're therefore referencing both elements in your array to the same object. Therefore, when you change "productObject" the final time in the loop, it affects all of the items in the array, because they are all pointing to the same exact object. What you need to do is have each element in the array point to a new instance of your object.

Upvotes: 1

Related Questions