Arrays

An array represents a fixed number of elements of a particular type. The elements in an array are always stored in a contiguous block of memory, providing highly efficient access.

An array is denoted with square brackets after the element type. For example:

	char[] vowels = new char[5];   // Declare an array of 5
	characters

Square brackets also index the array, accessing a particular element by position:

	vowels [0] = 'a';
	vowels [1] = 'e';
	vowels [2] = 'i';
	vowels [3] = 'o';
	vowels [4] = 'u';
	Console.WriteLine (vowels [1]);    // e

This prints “e” because array indexes start at zero. We can use a for loop statement to iterate through each element in the array. The for loop in this example cycles the integer i from 0 to 4:

	for (int i = 0; i < vowels.Length; i++)
	  Console.Write (vowels [i]);               // aeiou

Arrays also implement IEnumerable<T>, so you can enumerate members with the foreach statement:

	foreach (char c in vowels) Console.Write (c);   // aeiou

The Length property of an array returns the number of elements in the array. Once an array has been created, its length cannot be changed. The System.Collection namespace and subnamespaces provide higher-level data structures, such as dynamically sized arrays and dictionaries.

An array initialization expression specifies each element of an array. For example:

	char[] vowels = new char[] {'a','e','i','o','u'};

All arrays inherit from the System.Array class, which defines common methods and properties for all arrays. This includes instance properties ...

Get C# 3.0 Pocket Reference, 2nd Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.