Rony
Rony

Reputation: 345

Unable to make arrays in a list/arraylist

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 ??

Upvotes: 0

Views: 292

Answers (2)

Josh Maag
Josh Maag

Reputation: 643

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);

Upvotes: 1

LukeH
LukeH

Reputation: 269498

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

// ...

Upvotes: 5

Related Questions