An array is used to store a collection of data. It stores a fixed-size sequential collection of elements of the same type.
To declare an array, follow the below given syntax −
datatype[] arrayName;
Here,
- datatype is used to specify the type of elements in the array.
- [ ] sets the rank of the array. The rank specifies the size of the array.
- arrayName specifies the name of the array.
Let us now see an example −
int[] goals;
The following is an example showing how to declare and initialize arrays in C#.
Example
using System;
namespace Demo {
class MyArray {
static void Main(string[] args) {
int [] goals = new int[5] {3,2,1,5,4};
int i,j;
for (j = 0; j < 5; j++ ) {
Console.WriteLine("Goals in FIFA - Match[{0}] = {1}", j, goals[j]);
}
Console.ReadKey();
}
}
}Output
Goals in FIFA - Match[0] = 3 Goals in FIFA - Match[1] = 2 Goals in FIFA - Match[2] = 1 Goals in FIFA - Match[3] = 5 Goals in FIFA - Match[4] = 4