You are on page 1of 9

C# Arrays

Create an Array
Arrays are used to store multiple values in a single variable, instead of declaring separate variables
for each value.

To declare an array, define the variable type with square brackets:

string[ ] cars;

We have now declared a variable that holds an array of strings.

To insert values to it, we can use an array literal - place the values in a comma-separated list,
inside curly braces:

string[ ] cars = {"Volvo", "BMW", "Ford", "Mazda"};

To create an array of integers, you could write:

int[ ] myNum = {10, 20, 30, 40};

Access the Elements of an Array


You access an array element by referring to the index number.

string[ ] cars = {"Volvo", "BMW", "Ford", "Mazda"};


Console.WriteLine(cars[0]);

Change an Array Element


To change the value of a specific element, refer to the index number:

cars[0] = "Opel";
string[ ] cars = {"Volvo", "BMW", "Ford", "Mazda"};
cars[0] = "Opel";
Console.WriteLine(cars[0]);
Array Length
To find out how many elements an array has, use the Length property:

Example
string[ ] cars = {"Volvo", "BMW", "Ford", "Mazda"};
Console.WriteLine(cars.Length);

Other Ways to Create an Array


If you are familiar with C#, you might have seen arrays created with the new keyword, and
perhaps you have seen arrays with a specified size as well. In C#, there are different ways to create
an array:

string[ ] cars = new string[4];

string[ ] cars = new string[4] {"Volvo", "BMW", "Ford", "Mazda"};

string[ ] cars = new string[ ] {"Volvo", "BMW", "Ford", "Mazda"};

string[ ] cars = {"Volvo", "BMW", "Ford", "Mazda"};

It is up to you which option you choose. In our tutorial, we will often use the last option, as it is
faster and easier to read.

However, you should note that if you declare an array and initialize it later, you have to use
the new keyword:

string[ ] cars;

cars = new string[ ] {"Volvo", "BMW", "Ford"};

cars = {"Volvo", "BMW", "Ford"};


C# Array Operations using System.Linq
In C#, we have the System.Linq namespace that provides different methods to
perform various operations in an array. For example,
Example: Find Minimum and Maximum Element

using System;
using System.Linq;
namespace ArrayMinMax {
class Program {
static void Main(string[ ] args) {
int[ ] numbers = {51, 1, 3, 4, 98};
Console.WriteLine("Smallest Element: " + numbers.Min());
Console.WriteLine("Largest Element: " + numbers.Max());
Console.ReadLine();
}
}
}
Example: Find the Average of an Array

using System;
using System.Linq;
namespace ArrayFunction {
class Program {
static void Main(string[ ] args) {
int[ ] numbers = {30, 31, 94, 86, 55};
float sum = numbers.Sum();
int count = numbers.Count();
float average = sum/count;
Console.WriteLine("Average : " + average);
Console.WriteLine("Average using Average() : " + numbers.Average());
Console.ReadLine();
}
}
}

Output

Average : 59.2
Average using Average() : 59.2

In the above example, we have used

• numbers.Sum() to get the sum of all the elements of the array


• numbers.Count() to get the total number of element present inside the array
We then divide the sum by count to get the average.

float average = sum / count;

Here, we have also used the numbers.Average() method of the System.Linq namespace to
get the average directly.
Note: It is compulsory to use the System.Linq namespace while
using Min() , Max() , Sum() , Count() , and Average() methods.
Loop Through Arrays
Loop Through an Array
You can loop through the array elements with the for loop, and use the Length property to specify
how many times the loop should run.

The following example outputs all elements in the cars array:

Example
string[ ] cars = {"Volvo", "BMW", "Ford", "Mazda"};
for (int i = 0; i < cars.Length; i++)
{
Console.WriteLine(cars[i]);
}
Sort Arrays
Sort an Array
There are many array methods available, for example Sort(), which sorts an array alphabetically or
in an ascending order:

Example
string[ ] cars = {"Volvo", "BMW", "Ford", "Mazda"};
Array.Sort(cars);
for(int i=0;i<=cars.Length;i++)
{
Console.WriteLine(cars[i]);
}

int[ ] myNumbers = {5, 1, 8, 9};


Array.Sort(myNumbers);
foreach (int i in myNumbers)
{
Console.WriteLine(i);
}
Multidimensional Arrays
In the previous chapter, you learned about arrays, which is also known as single dimension
arrays. These are great, and something you will use a lot while programming in C#. However, if
you want to store data as a tabular form, like a table with rows and columns, you need to get
familiar with multidimensional arrays.

A multidimensional array is basically an array of arrays.

Arrays can have any number of dimensions. The most common are two-dimensional arrays (2D).

Two-Dimensional Arrays
To create a 2D array, add each array within its own set of curly braces, and insert a comma (,)
inside the square brackets:

Example
int[ , ] numbers = { {1, 4, 2}, {3, 6, 8} };

Access Elements of a 2D Array


To access an element of a two-dimensional array, you must specify two indexes: one for the array,
and one for the element inside that array. Or better yet, with the table visualization in mind; one
for the row and one for the column (see example below).

This statement accesses the value of the element in the first row (0) and third column (2) of
the numbers array:

Example
int[ , ] numbers = { {1, 4, 2}, {3, 6, 8} };

Console.WriteLine(numbers[0, 2]); // Outputs 2

Change Elements of a 2D Array


You can also change the value of an element.

The following example will change the value of the element in the first row (0) and first
column (0):
Example
int[ , ] numbers = { {1, 4, 2}, {3, 6, 8} };
numbers[0, 0] = 5; // Change value to 5
Console.WriteLine(numbers[0, 0]); // Outputs 5 instead of 1

Loop Through a 2D Array


You can easily loop through the elements of a two-dimensional array with a foreach loop:

Example
int[,] numbers = { {1, 4, 2}, {3, 6, 8} };

foreach (int i in numbers)

Console.WriteLine(i);

You can also use a for loop. For multidimensional arrays, you need one loop for each of the array's
dimensions.

Also note that we have to use GetLength() instead of Length to specify how many times the loop
should run:

Example
int[,] numbers = { {1, 4, 2}, {3, 6, 8} };

for (int i = 0; i < numbers.GetLength(0); i++)

for (int j = 0; j < numbers.GetLength(1); j++)

Console.WriteLine(numbers[i, j]);

}}

You might also like