Arrays in c#

Arrays
Array contains similar type of data. C# array index start from 0 means when size declared for array it goes to 0 to (size-1)
There is some difference of declaring array in other languages than C# see below syntax
int[] array; //not int array

Another detail is that the size of the array is not part of its type as it is in the C language. This allows you to declare an array and assign any array of int objects to it, regardless of the array's length.
int[] abc; // declare "abc" as an int array of any size

abc = new int[10];  // "numbers" is a 10-element array

abc  = new int[20];  // now it's a 20-element array

There are 3 types of arrays
1.       Single-dimensional array
2.       Multi-dimensional array
3.       Jagged Array

Declaring Single-dimensional array:

int[] array;

Declaring Multi-dimensional array:

int[,] array;

Declaring Jagged Array (array of array):

int[][] array;

Only declaration is not important for use of array in c#. You must have to instantiated before use like below:

Single-dimensional arrays:

int[] array = new int[5];
Multidimensional arrays:

string[,] array = new string[5, 4];

Array-of-arrays (jagged):

byte[][] array = new byte[5][];

for(int x = 0; x < array.Length; x++)
{
    array[x] = new byte[4];
}
You can also initialize array directly when declaring like below:

Single Dimensional array:

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

You can also initialize array without declaring size:

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

You can also remove new keyword from initialization:

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


Multidimensional Array:

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

Same as above we can initialize array without declaring size:

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

and also without new keyword:

int[,] array = { { 1, 2 }, { 3, 4 }, { 5, 6 } };

Jagged Array (Array-of-Arrays):

int[][] array = new int[2][] { new int[] { 2, 3, 4 }, new int[] { 5, 6, 7, 8, 9 } };

Without size:

int[][] array = new int[2][] { new int[] { 2, 3, 4 }, new int[] { 5, 6, 7, 8, 9 } };

Without “new” Keyword

int[][] array = { new int[] { 2, 3, 4 }, new int[] { 5, 6, 7, 8, 9 } };

Accessing an array element:

Single Dimensional array:

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

array[4] = 44;

Multidimensional array:

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

array[1, 1] = 5;

Jagged Array:

int[][] array= new int[2][] { new int[] { 2, 3, 4 }, new int[] { 5, 6, 7, 8, 9 } };

array[0][0] = 58;

array[1][1] = 667;




Post a Comment

0 Comments