Arrays in C#

Arrays in C#

In the previous tutorial,we are going to learn about implicit conversion, explicit conversion, parse and tryparse methods.

In this tutorial, we are going to learn about how to intialize values in arrays and how to retrieve values from the arrays and when it wil throw error in arrays

When to use Arrays?

Arrays are used when we want to store collection of items of similar data type. When we want to store elements in continuous blocks of memory, arrays are used.

Initializing and assigining values in an array

The below example shows how to intialize and stores values in an array.
eg: int[] numbers = new int[5]
The above line indicates that the array is of int type. and the reference is stored in numbers variable. 5 which we have written in new int[] indicates that we can store 5 elements of int type in numbers.
numbers[0] = 1; // stores value 1 in first memory location out of 5
numbers[1] = 2; // stores value 2 in second memory location out of 5
numbers[3] = 5; // stores value 5 in third memory location out of 5
The indexes in the array starts from 0. If we want to store or access the first element in an array we have to use numbers[0].The default values of the members of the array elements will be zero(0).We haven’t intialised elements in second, fourth positions.
So, By default values in second and fourth position will be zero.
numbers[2] //returns 0
numbers[4] //returns 0

We can also assign values to array in another way.
int[] numbers ={1,2,3}
But here it stores the values in 0,1,2 memory locations.

When errors will occur

eg: int[] numbers = new int[5];
Console.writeLine(numbers[10]) //Returns System out of bounds exception.
Here, we allocated space for five elements in the array but we are trying to access element stored at 10th index which we have not defined. So the compiler will throw an error

eg: int[] numbers = new int[5];
numbers[0] =”Geek”;
Here, we declared array of int type but we are storing string data type in int array. So compiler will throw an error.

Advantages and Disadvantages of Arrays


  • Arrays are strongly typed in C#. We cannot store one datatype in another datatype in arrays.
  • Easy to store and access values from Array
  • Arrays are stored in continuous memory blocks, this helps in greater accessing speed for modern CPU’s which have sophisticated caching methods


  • Arrays cannot grow in size, once intialised.
  • Have to rely on integral indices to store or retrieve items from the array

Leave a Reply

Your email address will not be published. Required fields are marked *