TOC

The community is working on translating this tutorial into Slovak, but it seems that no one has started the translation process for this article yet. If you can help us, then please click "More info".

Collections:

Arrays

Arrays works as collections of items, for instance strings. You can use them to gather items in a single group, and perform various operations on them, e.g. sorting. Besides that, several methods within the framework work on arrays, to make it possible to accept a range of items instead of just one. This fact alone makes it important to know a bit about arrays.

Arrays are declared much like variables, with a set of [] brackets after the datatype, like this:

string[] names;

You need to instantiate the array to use it, which is done like this:

string[] names = new string[2];

The number (2) is the size of the array, that is, the amount of items we can put in it. Putting items into the array is pretty simple as well:

names[0] = "John Doe";

But why 0? As it is with so many things in the world of programming, the counting starts from 0 instead of 1. So the first item is indexed as 0, the next as 1 and so on. You should remember this when filling the array with items, because overfilling it will cause an exception. When you look at the initializer, setting the array to a size of 2, it might seem natural to put item number 0, 1 and 2 into it, but this is one item too much. If you do it, an exception will be thrown. We will discuss exceptions in a later chapter.

Earlier, we learned about loops, and obviously these go great with arrays. The most common way of getting data out of an array, is to loop through it and perform some sort of operation with each value. Let's use the array from before, to make a real example:

using System;
using System.Collections;

namespace ConsoleApplication1
{
    class Program
    {
static void Main(string[] args)
{
    string[] names = new string[2];

    names[0] = "John Doe";
    names[1] = "Jane Doe";

    foreach(string s in names)
Console.WriteLine(s);

    Console.ReadLine();
}
    }
}

We use the foreach loop, because it's the easiest, but of course we could have used one of the other types of loop instead. The for loop is good with arrays as well, for instance if you need to count each item, like this:

for(int i = 0; i < names.Length; i++)
    Console.WriteLine("Item number " + i + ": " + names[i]);

It's actually very simple. We use the Length property of the array to decide how many times the loop should iterate, and then we use the counter (i) to output where we are in the process, as well as get the item from the array. Just like we used a number, a so called indexer, to put items into the array, we can use it to get a specific item out again.

I told you earlier that we could use an array to sort a range of values, and it's actually very easy. The Array class contains a bunch of smart methods for working with arrays. This example will use numbers instead of strings, just to try something else, but it could just as easily have been strings. I wish to show you another way of populating an array, which is much easier if you have a small, predefined set of items that you wish to put into your array. Take a look:

int[] numbers = new int[5] { 4, 3, 8, 0, 5 };

With one line, we have created an array with a size of 5, and filled it with 5 integers. By filling the array like this, you get an extra advantage, since the compiler will check and make sure that you don't put too many items into the array. Try adding a number more - you will see the compiler complain about it.

Actually, it can be done even shorter, like this:

int[] numbers = { 4, 3, 8, 0, 5 };

This is short, and you don't have to specify a size. The first approach may be easier to read later on though.

Let's try sorting the array - here's a complete example:

using System;
using System.Collections;

namespace ConsoleApplication1
{
    class Program
    {
static void Main(string[] args)
{
    int[] numbers = { 4, 3, 8, 0, 5 };

    Array.Sort(numbers);

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

    Console.ReadLine();
}
    }
}

The only real new thing here is the Array.Sort command. It can take various parameters, for various kinds of sorting, but in this case, it simply takes our array. As you can see from the result, our array has been sorted. The Array class has other methods as well, for instance the Reverse() method. You can look it up in the documentation to see all the features of the Array class.

The arrays we have used so far have only had one dimension. However, C# arrays can be multidimensional, sometimes referred to as arrays in arrays. Multidimensional arrays come in two flavors with C#: Rectangular arrays and jagged arrays. The difference is that with rectangular arrays, all the dimensions have to be the same size, hence the name rectangular. A jagged array can have dimensions of various sizes. Multidimensional arrays are a heavy subject, and a bit out of the scope of this tutorial.


This article has been fully translated into the following languages: Is your preferred language not on the list? Click here to help us translate this article into your language!