Arrays in C#

Creating Arrays in C#

A C# array may be created in a number of different ways. One way is to simply declare an array without initializing it with any values. The syntax for this is as follows:

type[] arrayname;

In the above example, type represents the type of data to be stored in the array (or example, string, int, decimal etc). The square brackets ([]) indicate that this is the declaration for an array and arrayname is the name by which the array is to referred.

For example, we can declare an array of strings called myColors as follows:

string[] myColors;

In this example, we have declared the array but not assigned any values to it. To assign values after an array has been declared the new statement must be used combined with a comma separated list of values:

string[] myColors;

myColors = new string[] {"red", "green", "yellow", "orange", "blue"};

An array may also be initialized in the declaration line simply by placing the comma separated list of values after the declaration:

string[] myColors = {"red", "green", "yellow", "orange", "blue"};

Another option is to declare the size of the array when it is created. For example, to declare an array of size 10 simply place the size value within the square brackets of the new statement:

myColors = new string[5];

This will reserve the space required for the full array without actually placing any values into the array. Finally, this approach may also be combined with the comma separated value list (although the number of values must match the size specified):

string[5] myColors = {"red", "green", "yellow", "orange", "blue"};

Declaring a Multidimensional Array

Multidimensional arrays are declared by placing commas within the square brackets. For example to declare a two dimensional array:

string[,] books;

A two dimensional array is initialized as follows:

	string[,] books = {
		            {"Macbeth", "Shakespear", "ID12341"},
			    {"Before I Get Old", "Dave Marsh", "ID234234"},
		            {"Security+", "Mike Pastore", "ID3422134"}
			  };

This creates a multidimensional array containing three rows and three columns. A row exists for each book, and each book contains three columns consisting of title, author and ID.

Accessing Array Values

Once values have been stored in an array it is highly likely that these values will need to be accessed at some later point in the C# code. This is achieved using the array accessor notation combined with the index into the array of the desired value. The array accessor is simply the array name followed by square brackets. Within the square brackets is placed a number representing the index into the array of the desired value (keeping in mind that the first array element in C# is index 0). For example, to access the second element of our myColors array the following notation would be used:

myColors[1];

For example:

string[] myColors = {"red", "green", "yellow", "orange", "blue"};

System.Console.WriteLine(myColors[1]);

When executed, the above code will output the word “green” since this is the string contained at index 1 position in the array.

Similarly, the value at a particular index point in the array may be changed using the accessor notation combined with the assignment operator (=). For example, to change the value of the first item in the array:

myColors[0] = "indigo";

Values in a multidimensional array may be accessed by specifying the index values for each dimension separated by commas. For example, to access the author (index position 1 of the second dimension) of the book located at index position 2 of the first dimension in our multidimensional array:

	System.Console.WriteLine(books[2,1]);

The above line of code will output the name “Mike Pastore” (i.e the author the 3rd book in the array).

Getting the Length of an Array

The length of a C# array may be obtained by accessing the Length property of the array in question. For example:

string[] myColors = {"red", "green", "yellow", "orange", "blue"};

System.Console.WriteLine ("Length of array = ", myColors.Length);

In the case of a multidimensional array, the Length property will contain the entire length of the array (including all dimensions). For example, our books two-dimensional array will have a length of 9.

Sorting and Manipulating C# Arrays

A number of methods are available as part of the System.Array package for the purpose of manipulating arrays.

An array may be sorted using the System.Array.Sort() method:

string[] myColors = {"red", "green", "yellow", "orange", "blue"};

System.Array.Sort (myColors);

for (int i=0; i<myColors.Length; i++)
{
	System.Console.WriteLine(myColors[i]);
}

The above example will sort the elements of the myColors array into alphabetical order:

blue
green
orange
red
yellow

The order of the elements may subsequently be reversed using the System.Array.Reverse() method:

System.Array.Reverse (myColors);

for (int i=0; i<myColors.Length; i++)
{
	System.Console.WriteLine(myColors[i]);
}

Resulting in the following output:

yellow
red
orange
green
blue

The values in an array may be cleared using the System.Array.Clear() method. This method clears each item in an array to the default value for the type (false for boolean, 0 for numeric and null for a string).

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s