ArrayList question

  • Thread starter Thread starter Guest
  • Start date Start date
G

Guest

Hi,

I have an application where I am attempting to pass an ArrayList of
ArrayList objects from a function to another function. I have created a
sample application as follows:

using System;
using System.Collections;

namespace ArrayListTest
{
class Class1
{
static void Main(string[] args)
{
ArrayList a1, a2;
a2 = null;

a1 = GetArrayList();
Console.WriteLine("Output");
for (int i = 0; i < a1.Count; i++)
{
a2 = (ArrayList)a1;
Console.WriteLine((string)a2[0] + "\t" + (int)a2[1]);
}
Console.ReadLine();
}

static ArrayList GetArrayList()
{
ArrayList result = new ArrayList();
ArrayList row = new ArrayList();

for (int i = 0; i < 3; i++)
{
row.Add(i.ToString());
row.Add(i);
result.Add(row);
}

return result;
}
}
}
Ideally this should output:

0 0
1 1
2 2

When I trace the code, the function contains an ArrayList of ArrayLists, as
expected, but when it gets passed to the main function, it seems to loose the
contents of the inner array list. I have also tried using "ref" to pass in
an ArrayList, rather than returning the ArrayList, but it still does not
work. Does anyone know why the program behaves like this? Thanks

Scott
 
Add the following code:

for (int i = 0; i < 3; i++)
{
row.Add (i.ToString());
row.Add (i);
result.Add (row);
row = new ArrayList() //Code to be added.
}

In the for loop your adding the same row arraylist reference to the
result arraylist.
 
Back
Top