Arrays and Collections
Storing groups of related items of data is a basic requirement of most software applications; the two primary was of doing this are with arrays and collections.
Arrays are collections of objects of the same type. Because arrays can be almost any length, they can be used to store thousands or even millions of objects, but the size must be decided when the array is created. Each item in the array is accessed by an index, which is just a number that indicates the position or slot where the object is stored in the arrsy. Arrays can be used to store both Reference Types and Value Types.
Single-Dimensional Arrays
An array is an indexed collection of objects. A single-dimensional array of objects is declared like this: type[] arrayName
Often, you initialize the elements in the array at the same time, like this:
int[] array = new int[5];
The default value of numberic array elements is zero, and reference elements default to null, but you can initialize values during array create, like this:
int[] array1 = new int[] {1, 3, 5, 7, 9};
int[] array2 = {1, 3, 5, 7, 9};
Arrays use zero-based indexes, so that the first element in the array is element 0.
Multidientsional Arrays
Conceptually, a multidimensional array with two dimensions resembles a grid. A multidimensional array with three dimensions resembles a cube.
Jagged Arrays
A variation of the multidimensional array is the jagged array: an array of arrays. A jagged array is a single-dimensional array, and each eleent is itself an array. The element arrays are not required to all be of the same size.
Using the foreach Statement
The foreach statement is often used to access each element stored in an array.
Arrays of Objects
Creating an array of objects, rather than an array of simple data types such as integers, is a two-part process. First you declare the array, and then you must create the objects that are stored in the array.
Collections
An array is just one of many options for storing sets of data by using C#. The option that you select depends on several factors, such as you intend to manipulate or access the items. For example, a list is generally faster than an array if you must insert items at the beginning or in the middle of the collections. Other types of collection classes include map, tree, and stack; each one has its own advantages.