Monday, February 18, 2008

Multidimensional Array in C#

Showing a simple example of a multidimensional array in c# because people coming from c++ background and all find it very difficult to make a multidimensional array in c#.

Here I am using a 2 dimensional array whose size is given in two textboxes,and later the values in the array is displayed in the listbox in the same form.

private void _addToArrayButton_Click(object sender, EventArgs e)
{
int total = 0;
int x, y = 0;
x = int.Parse(_firstPosText.Text);
y = int.Parse(_secondPosText.Text);
string[,] mulArray = new string[x, y];
for (int i = 0; i < x; i++)
{
for (int j = 0; j < y; j++)
{
total = i + j;
mulArray[i, j] = total.ToString();
}
}
for (int i = 0; i < x; i++)
{
for (int j = 0; j < y; j++)
{
_arrayList.Items.Add(mulArray[i, j].ToString());
}
}
}

A simple small example just to show the input to and output from a multidimensional array.

4 comments:

Anonymous said...

Of course, it occurs to me that if you're going to convert your 2D array into an ArrayList, you might as well just skip the intermediate step and insert the values into an ArrayList directly. Not to mention if you're storing a bunch of strings, it is more efficient to use a List instead of ArrayList.

Salu said...

Thanks for sharing your thoughts...

Salu said...

Thanks for sharing your thoughts...

Vimal Raj said...

Hi Simi,

its Good to hear that the post was useful for you. And Thanks for sharing the informative urls for the community.

Happy programming,
Vimal