An Array is a collection of values of a similar data type. Technically , C# arrays are a reference type. Each array in C# is an object and is inherited from the system . Array are declared as :
<data type> [] <identifier> = new <data type> [<size of array>];
Let’s define an array of type int to hold 10 integers.
int [] integers = new int [10];
The size of an array is fixed and must be defined before using it. However, you can use variables to define the size of the array :
int size = 10;
int [ ] integers = new int [size];
you can optionally do declaration and initialization in separate steps:
int [ ] integers ;
integers = new int [10];
It is also possible to define arrays using the values it will hold by enclosing values in curly brackets and separating individual values with a comma:
int [ ] integers = { 1, 2, 3, 4, 5 };
This will create an array of size 5, whose successive values will be 1, 2, 3, 4, 5.
Accessing the values stored in an array
To access the values in an array, we use the indexing operator [ int index]. We do this by passing an int to indicate which particular index value we wish to access. It’s important to note that index values in C# start from 0. So if an array contains 5 elements, the first element would be at 0, the second at index 1 and the last (fifth) at index 4. The following lines demonstrate how to access the 3rd element of array:
int [ ] interlay = { 5, 10, 15, 20 };
int j = interlay [2];
Let’s make a program that uses an integral array.
// demonstrates the use of arrays in c#
static void Main ( )
{
// declaring and initializing an array of type integer
int [ ] integers = { 3, 7, 2, 14, 65};
// iterating through the array and printing each element
for ( int I=0; I<5; I++)
{
Console.WriteLine ( integers [I ];
}
}
Ex. for (int I=0; I<integers. Length; I++ );
{
Console.WriteLine ( integers [I]);
}
foreach loop
There is another type of loop that is very simple and useful to iterate through arrays and collections . This is the foreach loop. The basic structure of a foreach loop is :
foreach (<type of elements in collection> <identifier> in <array or collection>)
<statement or block of statements>
Let’s now make our previous program to iterate through the array with a foreach loop:
// demonstrates the use of arrays in C#
static void Main ( )
{
// declaring and initializing an array of type integer
int [ ] integers = { 3, 7, 2, 14, 65};
// iterating through the array and printing each element
foreach ( int I in integers)
{
Console.WriteLine (I );
}
}
foreach (int I in integers )
Ex. static void Main ()
{
string name = ” Faraz Rashed”;
foreach (char ch in name)
{
Console.WriteLine (ch);
}
}