Arrays in C#, One Dimensional Arrays, Multi Dimensional Arrays, Jagged Arrays in C#

 

A collection of homogeneous or same type of elements is called as an Array. Arrays shares same name with different index numbers. Arrays index will begin from zero(0). Arrays will be stored in continuous memory hence accessing is faster and arrays stored in heap memory because arrays are reference types. 

As arrays are reference types, these will store some default values. Arrays are instances of a predefined class System.Array. There are three defined types of Arrays in C#, those are One-Dimensional Arrays, Multi-Dimensional Arrays and Jagged Arrays.

 

C# One Dimensional Arrays: 

If the array contains set of values in single row it is called One-Dimensional arrays. We can defined one dimensional arrays in C# in two different ways either mentioning the size while declaring the array or assigning the values directly while declaring the arrays itself.

 

        int[] Numbers = new int[5]; 

        Numbers[0] = 1; 

        Numbers[1] = 2; 

        Numbers[2] = 3; 

        Numbers[3] = 4; 

        Numbers[4] = 5;

 

As shown above we can mention size while declaring the array and assign values later or assign the values while declaring the arrays itself as shown below.

 

int[] Numbers = new int[] { 1, 2, 3, 4, 5 };

 

In C# int and float type arrays default value is zero(0), char type arrays default value is null, bool type arrays default value is false and datetime type arrays default value is 1/1/0001 12:00:00 AM.

 

C# Multi Dimensional Arrays: 

If elements in a arrays arranged in Rows and Columns is called as Multidimensional arrays. Multidimensional arrays size will be represented by number of rows/number of columns. All rows must contain same number of elements in C# multi dimensional arrays.

 

int[,] Numbers = new int[,] {{1,2},{3,4},{4,5}};

 

As shown above we can declar Multi dimensional arrays.

 

C# Jagged Arrays: 

Jagged arrays in C# are same as Multi dimensional arrays but each row in Jagged array may contain different number of elements because of this jagged arrays can save the memory. Jagged arrays in C# are faster in access. We can call jagged arrays as "Dynamic Arrays" or "Array of Arrays". 

We can declar jagged arrays as shown below.

 

        int[][] Numbers = new int[2][];   

        Numbers[0] = new int[] { 1, 2, 3 }; 

        Numbers[1] = new int[] { 4, 5, 6, 7, 8};

 

As shown above we have jagged array Numbers with two rows. First row has three elements while second row has 5 elements because in C# jagged arrays each row can contain different number of elements.