Arrays in C#

I always liked the concept of arrays. Being able to conceptually visualize in multiple dimensions took me some time to get my mind around, but in the end I was successful. The example here will discuss 2 dimensional arrays of type single, multiple and jagged.

A single dimensional array is the simplest. You simply code an object 1 column by (n) rows. Like this image and code represent:

[sourcecode language="csharp" padlinenumbers="true" autolinks="false" gutter="false" toolbar="false"]
int[] singleDimensionalArray = new int[2];
[/sourcecode]

image

The single dimension array is of type integer with a single column and [2] rows defined. Take note that the numbering of arrays always starts with 0 and not with one. If you wanted to access the value stored in the first row you would use;

[sourcecode language="csharp" autolinks="false" gutter="false" toolbar="false"]
int firstRow = singleDimensionalArray[0];
[/sourcecode]

image

And this code:

[sourcecode language="csharp" autolinks="false" gutter="false" toolbar="false"]
int[,] multiDimensionalArray = new int[2, 2];
[/sourcecode]

Again, I coded this one of type integer with a structure of 2 by 2, I.e. [2, 2]. This means I have a table 2 columns wide by 2 rows deep. If you needed to access the value (210) stored in [1, 0] the following would provide it:




[sourcecode language="csharp" autolinks="false" gutter="false" toolbar="false"]
int multValue = multiDimensionalArray[1, 0]
[/sourcecode]

The final type of array discussed here is called a Jagged array. This array allows you to have arrays embedded within arrays of different length of a single type.

[sourcecode language="csharp" autolinks="false" gutter="false" toolbar="false"]
int[][] jaggedArray = new int[2][];
 
jaggedArray[0] = new int[4];
jaggedArray[1] = new int[7];
[/sourcecode]

image

To access the value 501 stored at location [1][4] you would used this code:

[sourcecode language="csharp" autolinks="false" gutter="false" toolbar="false"]
int jaggedValue = jaggedArray[1][4];
[/sourcecode]

Download the source here.




Leave a Comment

Your email address will not be published.