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:
- Code reusability
- Random access
- Less code
- Easy traversing
- Easy manipulation
- Can't increase its size at runtime.
Types of array:
- Single dimensional array
- Multi dimensional array
- Jagged array
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 30Declaring 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 60Traversing 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