Home and Learn: C# NET Course

Multi Dimensional Arrays In C# .Net


<< Continues from the previous lesson

Your arrays don't have to be single lists of items, as though they a were a column in a spreadsheet: you can have arrays with lots of columns and rows. These are called Multi-Dimensional arrays. For a 1-dimensional array, the ones you've been using, it would look like this:

A Single Dimension Array

For a 2-dimensional array, it would look like this:

A Multi Dimension Array

So if you wanted to get at the value of 2000 in the table above, this would be at array position 1 in column 2 (1, 2). Likewise, the value 400 is at position 3, 1.

To set up a 2-dimensional array, you use a comma:

int[ , ] arrayTimes;

You then need a number either side of the comma:

arrayTimes = new int[5, 3];

The first digit is the number of Positions in the array; the second digit is the number of Columns in the array.

Filling up a 2-dimensional array can be quite tricky because you have to use loops inside of loops! Here's a programme that fills a 2-dimensional array with the values in the table above:

C# .NET Code to fill a Multi Dimensional Array

Notice the two for loops in the code above, one inside of the other. The first loop is setting the value of the Rows (array Positions), and the second loop is setting the value of the Columns.

You don't have to understand the code, at this stage of your career! But see if you can puzzle it all out. For the adventurous, add another button to your form. Enter the code above. Now add a second double for loop, and print out the array values in your list box. See if you can get the same values as ours, in the form below:

C# .NET Form - Multi Dimension Array

This is a tough exercise, so give yourself a giant pat on the back, if you get there!

In the next lesson, you'll see how to deal with Arrays and Text.

back to the c# net contents page


Buy the Book of this Course

Email us: enquiry at homeandlearn.co.uk