Introduction

Array is a collection of similar elements. With array declaration, you can store multiple items of same type using a single variable and still access these elements individually by using the index, when required. In c#, the array index starts at zero.

Array provides a means of declaring multiple items that are of same type by using single variable. Each item of an array is easy designated with the help of integer value called index. The first item in a C# array is accessed by index 0. Since C# array is zero based. The index of the last item in an array is one less than the number of items in the array.

Example

array of 10 element


The first item is zero away from the start of the array. The second item is one away from the start of the array and so on.

How to declare an array

In C# you can declare array using square bracket. First, you specify the data type of the array followed by the open and close square bracket, than you enter the name of the variable. Shown in fig 1.1:

declare an array

Fig 1.1

The square brackets identify the rank or the number of dimensions for the array. In this case, it is an array of rank one.

Fig 1.1, show the array with rank one. Commas within the square brackets define additional dimension. It defines a two dimension array of cell. Fig 1.2 show two dimension array:

two dimension array
Fig 1.2

Fig 1.2, show the array has a rank of two. Additional dimensions are added, with additional comma, and the total rank is one more than the number of commas.

Initializing and Assigning array

Once an array is declared, it is necessary to assign the values in an array. This can be done by various methods one is show in this tutorial:

Program code

This is the basic program that will show you how to use an array:
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Text;
  5. using System.Threading.Tasks;
  6. namespace DemoArray
  7. {
  8. class Program
  9. {
  10. static void Main(string[] args)
  11. {
  12. int[] item = new int[10]; //declation and initilization of an array
  13. Console.WriteLine("Enter the 10 elements :");
  14. try
  15. {
  16. for (int i = 0; i < 10; i++)
  17. {
  18. item[i] = Int32.Parse(Console.ReadLine());
  19. }
  20. Console.WriteLine("\n Output: \n");
  21. }
  22. catch (Exception e)
  23. {
  24. Console.WriteLine(e.Message);
  25. }
  26. for (int j = 0; j < 10; j++)
  27. {
  28. Console.WriteLine("Element {0} is: {1}", j, item[j]);
  29. }
  30. Console.ReadLine();
  31. }
  32. }
  33. }
Output

array program output