We often have a situation where we need to use a couple of variables of the same type and to execute the same operation on each of them. Imagine if we need hundreds of variables or even more, well we can agree upon a fact that creating a hundred variables of the same type is not a solution.

Fortunately, C# provides us with a complex type named array.

Support Code Maze on Patreon to get rid of ads and get the best discounts on our products!
Become a patron at Patreon!

For the complete navigation of this series check out: C# Back to Basics.

To download the source code, visit Arrays in C# Source Code.

Arrays are the reference data types that consist of data of the same type, arranged in the sequential collection. We can access any information inside an array by stating the name of the array and the position of the data. The data position inside an array is called Index. In arrays, indexes are zero-based. That means that the first element is stored in the index zero and the last element is on the array Length – 1 index. So, if our array has 5 elements, indexes are addressed from 0 to 4.

This post is divided into several sections:

Array Declaration and Initialization

To declare an array we state the type of that array then the square brackets and finally the name of that array:

int[] numbers;
Pen[] pens;

The important thing to know is that no matter whether we store the reference type or the value type data inside an array, the array is always a reference data type.

To initialize our arrays we need to use a new keyword then the data type and finally the square brackets with the array capacity inside:

numbers = new int[5];
pens = new Pen[5];

In a first example, we store the type int (value type) inside the numbers array thus reserving the space in our memory for five integers. But in the second example, we are reserving the space in our memory for five Pen types (reference types) so we are not storing their values but their references. All the Pen values are null for now.

Until now, we have just allocated the memory for our values, we didn’t actually add those values at all. So, to finish the initialization process we need to add values to our arrays. The most common way is to declare, allocate and initialize an array in one line of code:

int[] arrayExample = new int[5] { 4, 5, 7, 8, 3};
Pen[] penArrayExample = new Pen[3] { new Pen(Color.Red), new Pen(Color.Green), new Pen(Color.Blue) };

We can use the indexes as well, to populate an array:

int[] numbers = new int[2];
numbers[0] = 5; numbers[1] = 7;

Array Manipulation

To manipulate with an array, we can use a for loop. With a for loop we are using indexes to access each element of an array:

static void Main(string[] args)
{
    int[] numbers = new int[5] { 4, 5, 7, 8, 3};
           
    for(int i = 0; i < numbers.Length; i++)
    {
        Console.WriteLine(numbers[i]);
    }
}

We can do the same thing but with the foreach loop. Difference between these two approaches is because with the for loop we are using indexes to access elements (variable i), but with the foreach loop we are not using indexes but the actual values:

static void Main(string[] args)
{
    int[] numbers = new int[5] { 4, 5, 7, 8, 3};

    foreach(int i in numbers)
    {
        Console.WriteLine(i);
    }
}

Examples

Example1: Create an application in which we create an array of n elements, populate that array with the random integer numbers, and finally print out all those numbers and their sum:

class Program
{
    //array is a reference type so every action in this method will affect original array
    public static void PopulateArray(int[] numbers)
    {
        Random r = new Random();
        for(int i = 0; i < numbers.Length; i++)
        {
            numbers[i] = r.Next(1, 101);
            Console.WriteLine($"The {i+1}. element is {numbers[i]}");
        }
    }

    public static void CalculateSum(int[] numbers)
    {
        int sum = 0;
        foreach (int i in numbers)
        {
            sum += i;
        }

        Console.WriteLine($"The sum of all the elements is {sum}");
    }

     static void Main(string[] args)
    {
        Console.WriteLine("Enter an array capacity: ");
        int capacity = Convert.ToInt32(Console.ReadLine());

        int[] numbers = new int[capacity];

        PopulateArray(numbers);
        Console.WriteLine();
        CalculateSum(numbers);

        Console.ReadKey();
    }
}

Example Arrays in C#

Parameter Arrays

A params array enables us to pass a variable number of arguments to a method. To create a params array we must specify the params keyword when we specify the parameters for our method:

public static void TestMethod(params int[] numbers)
{
    //method body	
}

The effect of the params keyword is that it allows us to send any number of arguments to the method’s parameter without creating an array:

static void Main(string[] args)
{
   TestMethod(1, 2, 3);
}

Even though a params array is very useful, we still have some limitations while working with them:

  • We can’t use params keyword to work with two-dimensional arrays
  • Method overloading is not possible solely with the params keyword
  • We can’t specify ref or out keywords with params arrays
  • A params array has to be the last parameter in our method
  • A non-params method always take priority over the params methods

Example2: Create an application that prints out the minimum of all the numbers sent to the PrintMin method:

class Program
{
    public static void PrintMin(params int[] numbers)
    {
        int min = numbers[0];
        for(int i=1; i < numbers.Length; i++)
        {
            if(min > numbers[i])
            {
                min = numbers[i];
            }
        }

        Console.WriteLine(min);
    }
    static void Main(string[] args)
    {
        PrintMin(49, 58, 12, 98, 47, 13);

        Console.ReadKey();
    }
}

Multi-Dimensional Array

We know how to use single-dimensional arrays, but C# supports multi-dimensional arrays as well. In this section, we are going to talk about two-dimensional arrays. Why are they called two-dimensional?

Well, because they have two dimensions, rows and columns. To create “2d” array, we are using the following syntax:

int[,] numbersMultiDim = new int[3, 2] { { 1, 5 }, { 3, 8 }, { 6, 1 } };

With this syntax, we create a two-dimensional array with three rows and two columns. So, in a graphical presentation it should look like this:

Multi-dimensional Arrays in C#

To access any number from this array we can use the syntax with the name of the array and the position of the number between square brackets. We are providing position by using indexes. So, the first row has the index 0 and the last one has the index (number of rows – 1). It is the same with the columns:

int number = numbersMultiDim[2, 1]; // value 1    => third row on index 2 and second column on index 1

To iterate through all the data we can use the for loop:

for(int i = 0; i < numbersMultiDim.GetLength(0); i++)
{
      for(int j = 0; j < numbersMultiDim.GetLength(1); j++)
      {
          Console.WriteLine(numbersMultiDim[i,j]);
      }
}

As you can see, we are using two loops to iterate through a two-dimensional array. First one is iterating through all the rows and the second one through all the columns in the current row.

We use multidimensional arrays when we have to present our data in the multidimensional form. Specifically, we use two-dimensional arrays to work with the data in a table form with the rows and columns.

Conclusion

Great job. We have all the required knowledge to work with arrays and to use them in our development process.

In the next part of the series, we are going to talk about StreamWriter and StreamReader classes in C#.

Liked it? Take a second to support Code Maze on Patreon and get the ad free reading experience!
Become a patron at Patreon!