An array is a collection of data objects of the same type. An array creates one variable, rather than declaring multiple variables to store data.
That one variable is allocated to a contiguous memory space where all the data is stored. An array may be of type int
, char
, string
and even an array
itself.
The values stored in the array are referred to as elements and each element is present at a particular index of the array.
The syntax to define an array is:
datatype[] arrayName;
datatype
: The type of objects that will be stored in the array eg. int
, char
etc.
[ ]: Specifies that the declared variable points to an array
arrayName: Specifies the name of the array
Defining an array does not initialize it. In order to store values in the array, we must initialize it first, the syntax of which is as follows:
data-type [ ] arrayName = new data-type [size];
Look at the following examples to get a better idea about array initialization:
using System;class HelloWorld{static void Main(){int[] array = new int[5];}}
class HelloWorld{static void Main(){int[] array = new int[5]{5,4,3,2,1};}}
class HelloWorld{static void Main(){int[] array = {1,2,3,4,5};}}
Note: If the
new
keyword is used, the array is initialized on the heap otherwise it is initialized on the stack.
The elements of an array can be accessed through their indices.
Suppose we wish to access the fourth element 2. To do so, we will proceed as follows:
using System;class HelloWorld{static void Main(){int[] array = new int[5]{1,3,5,2,4};int x = array[3];Console.WriteLine(x);}}
Another way of accessing array elements is by using the built-in GetValue()
function.
using System;class HelloWorld{static void Main(){int[] array = new int[5]{1,3,5,2,4};int x = (int) array.GetValue(3);Console.WriteLine(x);}}
The length or size of the array can be determined using the built-in Length
function.
using System;class HelloWorld{static void Main(){int[] array = new int[5]{1,3,5,2,4};int length = array.Length;Console.WriteLine(length);}}
The element stored at a particular index in the array can also be modified using the following syntax:
using System;class HelloWorld{static void Main(){int[] array = new int[5]{1,3,5,2,4};//Modifying the first elementarray[0] = 999;//Printing the entire arrayfor (int i = 0; i < array.Length; i++){Console.WriteLine(array[i]);}}}
Arrays are one of the fundamental data structures in C#. The ability to store multiple items of the same data-type make them incredibly useful for complex programming problems.