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
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:
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:
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:
By using new keyword:
The use of new keyword tells the runtime to allocate memory for the data type. When you use the new keyword as part of an array assignment, you must specify the size of the array within the square brackets. Shown in fig 1.3:
Fig 1.3
Program code
This is the basic program that will show you how to use an array:
- using System;
- using System.Collections.Generic;
- using System.Linq;
- using System.Text;
- using System.Threading.Tasks;
-
- namespace DemoArray
- {
- class Program
- {
- static void Main(string[] args)
- {
- int[] item = new int[10];
- Console.WriteLine("Enter the 10 elements :");
- try
- {
- for (int i = 0; i < 10; i++)
- {
- item[i] = Int32.Parse(Console.ReadLine());
- }
- Console.WriteLine("\n Output: \n");
- }
- catch (Exception e)
- {
- Console.WriteLine(e.Message);
-
- }
- for (int j = 0; j < 10; j++)
- {
- Console.WriteLine("Element {0} is: {1}", j, item[j]);
- }
- Console.ReadLine();
- }
- }
- }
Output