Changes

Jump to: navigation, search

Introducing C Sharp Arrays

2,016 bytes added, 19:35, 22 January 2008
Accessing Array Values
myColors[0] = "indigo";
</pre>
 
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 1 of the second dimension)of the book located at index 2 of the first dimension in our multidimensional array:
 
<pre>
System.Console.WriteLine(books[2,1]);
</pre>
 
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:
 
<pre>
string[] myColors = {"red", "green", "yellow", "orange", "blue"};
 
System.Console.WriteLine ("Length of array = ", myColors.Length);
</pre>
 
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:
 
<pre>
string[] myColors = {"red", "green", "yellow", "orange", "blue"};
 
System.Array.Sort (myColors);
 
for (int i=0; i<myColors.Length; i++)
{
System.Console.WriteLine(myColors[i]);
}
</pre>
 
The above example will sort the elements of the myColors array into alphabetical order:
 
<pre>
blue
green
orange
red
yellow
</pre>
 
The order of the elements may subequently be reversed using the ''System.Array.Reverse()'' method:
 
<pre>
System.Array.Reverse (myColors);
 
for (int i=0; i<myColors.Length; i++)
{
System.Console.WriteLine(myColors[i]);
}
</pre>
 
Resulting in the following output:
 
<pre>
yellow
red
orange
green
blue
</pre>
 
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).

Navigation menu