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. The following declares an array of five characters:
char vowels = new char;
Square brackets also index the array, accessing a particular element by position:
vowels = 'a'; vowels = 'e'; vowels = 'i'; vowels = 'o'; vowels = 'u'; Console.WriteLine (vowels ); // e
This prints “e” because array indexes start at 0. We can use a
for loop statement to iterate through
each element in the array. The
in this example cycles the integer
for (int i = 0; i < vowels.Length; i++) Console.Write (vowels [i]); // aeiou
Arrays also implement
IEnumerable<T> (see Enumeration and Iterators), so you can also enumerate members
foreach (char c in vowels) Console.Write (c); // aeiou
All array indexing is bounds-checked by the runtime. An
IndexOutOfRangeException is thrown if you use an
vowels = 'y'; // Runtime error
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 lets you declare and populate an array in a single step: ...