Arrays are zero based, fixed size collection of elements, meaning first index of an Array is 0, and once we initialize an array it’s size cannot be changed. Array is an reference type. System.Array class holds static and instance methods that we can use with arrays.



Arrays can can contain reference or value types. We declare an Array with type followed by [] (square brackets) and variable:



As Arrays are an reference type we initialize it by assigning Array variable to Array instance but instead of using round brackets after instance type we use square brackets which should hold integer value. That value is specifying size of our Array and that value cannot be changed. If input number 3 inside square brackets, first index will be 0 and last will be 2. We can also use var keyword while initializing an Array.



Populating an array with values


Example shows array of city names that can hold 3 elements and multiple approaches to populating an array with values:



How to use arrays

Retrieve value

We retrieve an element from array by specifying index of that value. If for example we wanted to retrieve first element from our previous array we can access that value like this:


Approach 1 is commonly known as manual initializer, and Approaches 2 and 3 are known as collection initializers.

Iterate through array

We can iterate an arrays using for and foreach statements



Find index of an value

Change value of an element

Detect if array holdes speciffic value

Lenght of an array



Q:What will happen if we try to add more element to an array than array can hold?

A: Compiler warning will be received.


Q:What will happen if we try to add less element to an array than array can hold?

A: Not populated elements will be null.



Q: What will happen if we try access element of an array that is out of scope of an array?

A: IndexOutOfRangeException will occur.


Q: What will happen if we try to find index value of an element if that element does not exist inside of an array?

A: You will get value -1.


Good practices for using arrays:

Use plural variable name. Variable name cityNames is better naming convention than cityName.

Use arrays only if you know array size during design time because array size cannot be changed during runtime.

Populate your arrays with collection initializer technique because they are less error prone and easier to read.