An Array is an unordered sequence of elements. All the elements in an array have the same type, followed by a pair of square brackets, followed by the variable name.
int[] pinNumbers; //personal identification numbers
note: C and C++ programmers should note that the size of the array is not part of thedeclaration.
Arrays are reference type
The size of an array does not have to be a constant, it can be calculated at run time.
int size = int.Parse(Console.ReadLine());
int[] pinNumbers = new int[size];
Its possible to create arrays of size 0. Useful in situations where the size is determined dynamically. Array with size 0 is not a null array.
Initializing Array Variable
i.e Initializing pinNumbers to an array of 4 int with the following values: 9,3,7,2
int[] pinNumber = new int[4] {9,3,7,2};
// the number in the curly bracket must match the size of the array
the value within the curly brace do not have to be constants.
Random r = new Random();
int[] pinNumber = new int[4]{ r.next() %10, r.next() %10,
r.next() %10, r.next() %10};
note: The system.Random class is a pseudo -random number generator. The Next method returns a nonnegative random number.
When initializing an array, you can omit the 'new' expression and the size of the array:
int[] pinNumbers {9,7,3,2};
Accessing Individual Array Elements
To access an individual array element you must provide an index indicating which element you require.
int myNumber;
myNumber = pinnumbers[3] ;
you can also change the contents of an array by assigning a value to an indexed element:
myNumber = 167;
pinnumbers[2] = myNumber;
the initial element in an array is indexed 0 (zero) and not 1.
All array elements access is bounds-checked. when using an integer index that is less than 0 or greater than or equal to the lengh of the array, the compiler throws an indexOutOfRangeException
try
{
int[] pinnumbers ={9,3,7,2};
Console.WritLine(pinNumber[4]); //error, the 4th element is at index 3
}
catch(indexOutOfRangeException ex)
{
...
}