0

I need to make array in a arraylist or in a list, I used this:

List<string[]> OL = new List<string[]>();
string[] OLdata = new string[7];

OLdata[0] = .. ; OLdata[1] = .. OLdata[6] = ..
OL.Add(OLdata);

and I can access it with

    OL[0].GetValue(3) or OL[0][3] ..

again writing to OLdata and adding it in OL list, when I try to access data with

    OL[0][3] ..

I am getting the new data which was inserted in array, I am obviously expecting different values in OL[0][3] and OL[1][3] , whats the reason or any other suggestion ??

3
  • 1
    When you write to OLdata the second time how do you do it? Commented Nov 1, 2011 at 14:13
  • In your code you have not added a second array. To be honest with you, since I don't see a second Add statement I'd say accessing OL[1][3] this way should throw an exception. If you've just added OLdata twice, then I would have to +1 @LukeH's answer. Commented Nov 1, 2011 at 14:16
  • I think there are mistakes in your question. OL[0] = ..; OL[1] = ... should be OLdata[0] = ...; OLdata[1] = ... Commented Nov 1, 2011 at 14:17

2 Answers 2

5

Arrays are reference types, so all you're actually doing is altering and then adding the same array object multiple times.

You should probably do something like this instead, creating and populating a new array each time:

var olData = new string[7];  // create first array
olData[0] = ...  // etc
ol.Add(olData);  // add first array

olData = new string[7];  // create second array
olData[0] = ...  // etc
ol.Add(olData);  // add second array

// ...
Sign up to request clarification or add additional context in comments.

4 Comments

o yea..any solution to that ?
@Rony the "new" on olData needs to be called every time you want a new item in the list.
+1 - I see in his description where he is simply adding the same object as a second element. He's probably also surprised to see his new addition appearing in OL[0] as well.
I would argue this really should not be done. It really sounds like he should make the collection a property of a class and make reference a collection of that class.
1

When you add your second string array, are you creating a new string[7]?

E.G.

List<string[]> OL = new List<string[]>();
string[] OLdata = new string[7];

OL[0] = .. ; OL[1] = .. OL[6] = ..
OL.Add(OLdata);

OLdata = new string[7];

OL[0] = .. ; OL[1] = .. OL[6] = ..
OL.Add(OLdata);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.