C# Arrays

Like in other programming languages, in C# the array can be defined as a collection of similar type of objects which have contiguous memory allocation. Array index starts from zero(0). It is an object of the base class System.Array .


Advantages of using arrays:
  1. Code reusability
  2. Random access
  3. Less code
  4. Easy traversing
  5. Easy manipulation
Disadvantages:
  1. Can't increase its size at runtime.
Collections are used in C# to overcome size related problems of array.

Types of array:
  1. Single dimensional array
  2. Multi dimensional array
  3. Jagged array
Single Dimensional Array Single dimensional array is the array which has a single dimension and doesn't require any row or columns on a high level. It is stored in contiguous memory location.
Declaring 1D Array : To declare 1D array, we have to use square brackets [] after the data type. Let's see the syntax:

Syntax
<data type>[] <variable-name> = new <data type>[<size>];
Example:
int[] arr=new int[5]
let's see a simple example which initialize and traverse 1D array
using System;  
public class ArrayExample  
{  
public static void Main(string[] args)  
{  
int[] arr = new int[5];//creating array  
arr[0] = 10;//initializing array  
arr[2] = 20;  
arr[4] = 30;  
//traversing array  
for (int i = 0; i < arr.Length; i++)  
{  
Console.WriteLine(arr[i]);  
}  
}  
}
Output
10
0
20
0
30
Declaring and initializing 1D array at the same time: We can declare and initialize 1D array at the same time. Let's see how can we do it . int[] arr=new int[5]{10,20,30,40,50}; We are not required to use size int[] arr=new int[]{10,20,30,40,50}; We can omit new operator also Int[] arr={10,20,30,40,50}; Let's see a simple example of initializing 1D array.
using System;
public class ArrayExample1
{
            public static void Main(string[] args)
            {
                        int[] arr={10,20,30,40,50,60};
                        for(int i=0;i<arr.Length;i++)
                        {
                                    Console.WriteLine(arr[i]);
                        }
            }
}
Output
10
20
30
40
50
60
Traversing array using foreach loop
We can use foreach loop in C# to traverse array elements. Let's see how can we do it.
using System;  
public class ArrayExample  
{  
public static void Main(string[] args)  
{  
int[] arr = { 10, 20, 30, 40, 50 };//creating and initializing array  
//traversing array  
foreach (int i in arr)  
{  
Console.WriteLine(i);  
}  
}  
}
Output
10
20
30
40
50