C# Array: Using Arrays in C#

Arrays in C# are easy to use, unlike their pricklier C++ relatives.

In this article we'll take a look at some code examples that demonstrate how arrays are used. But before you jump in there with that array, ask yourself if you mightn't need a List instead. Arrays in C# are lightweight and straightforward, but they are not resizeable. If you need a resizeable array, what you actually want is a List. With that caveat, we'll continue ....






There are several different ways to declare and simultaneously initialize an array.

You can also declare a variable of an array type, but not actually make it refer to anything at all. Here are examples of the possibilities:

 // Declare the array reference but don't initialize it.
int[] values;

// Declare the array reference, initialize it to
// an array able to hold 4 ints; don't put anything
// in the array.
int[] values1 = new int[4];

// Declare the array reference and set it equal
// to an array of four specific ints.
int[] values2 = new int[] { 1, 3, 4, 6 };

// Same as the above, but nicer.
int[] values3 = { 1, 4, 7, 4 };




Putting Objects in Arrays



Of course, you're not stuck with declaring int arrays. You can put any object in a C# array. The only catch is that you can only put one type of object in an array.

Actually -- that's not strictly true; polymorphism means that you can put any object or any derived object in an array.

Which, as we'll see later, makes arrays pretty flexible.

Let's take a look at an example.

using System;

namespace ConsoleApplication1
{
    class Parent
    {
        // Code and variables go here!
    }

    class Child : Parent
    {
        // Child derives from Parent.
    }
   
    class Program
    {
        static int Main(string[] args)
        {
            Parent parent1 = new Parent();
            Parent parent2 = new Parent();
            Child child1 = new Child();

            Parent[] objects = new Parent[]{parent1, parent2, child1, new Child(), new Parent()};

            return 0;
        }
    }
}





This little program declares an array of Parent objects and puts three Parent objects and two child objects in it. As you can see, you can even use the new keyword within the array.

Iterating Over Arrays in C#



We can iterate through arrays using foreach or just a plain old trusty for loop like back in the olden days of yore.

In the following program we enlarge the above program so that the Parent object has a virtual (overrideable) method called Speak(); the Child object then overrides the speak method. Then we iterate through the array and call the method of each object.


using System;

namespace ConsoleApplication1
{
    class Parent
    {
        virtual public void Speak()
        {
            Console.WriteLine("Do your homework!");
        }
    }

    class Child : Parent
    {
        override public void Speak()
        {
            Console.WriteLine("I don't want to!");
        }
    }
   
    class Program
    {
        static int Main(string[] args)
        {
            Parent parent1 = new Parent();
            Parent parent2 = new Parent();
            Child child1 = new Child();

            Parent[] objects = new Parent[]{parent1, parent2, child1, new Child(), new Parent()};

            // Iterate over the array with foreach
            foreach(Parent obj in objects)
            {
                obj.Speak();
            }

            Console.WriteLine("------------");

            // Iterate using for
            for (int i = 0; i < objects.Length; i++)
            {
                objects[i].Speak();
            }

            // Wait for a keypress
            Console.ReadKey();

            return 0;
        }
    }
}





Do your homework!
Do your homework!
I don't want to!
I don't want to!
Do your homework!
------------
Do your homework!
Do your homework!
I don't want to!
I don't want to!
Do your homework!




Notice that the for loop uses the array's Length property to know how many loop iterations to make.

Multidimensional Arrays



You can declare and initialize a multidimensional array in C# as follows.

 int[,] grid = {
                               {1, 2, 4},
                               {0, 4, 3},
                               {1, 6, 4}
                           };




Using this kind of syntax, all the sub-arrays have to be the same length. However, we can create arrays where the sub-arrays are of different lengths. In C#, this is called a jagged array.

The key to doing this (and to understanding multidimensional arrays in general), is to realize that we are really only declaring an array of references, where each of the references happens to point to an array.

So if you have a multidimensional array, the first pair of index brackets gets you the appropriate element of the array (which is a reference), while the second pair gets you the appropriate element of the array that this reference points to.

Clear as mud?

Let's take an example.

using System;

namespace ConsoleApplication1
{   
    class Program
    {
        static int Main(string[] args)
        {
            // Declare a multidimensional array
            int[][] multi = {
                          new int[]{1, 3, 4},
                          new int[]{2, 6},
                          new int[]{0, 4, 6, 3}
                      };

            // We can change the elements of the 'inner' array
            // if we want.
            multi[1] = new int[] { 9, 9, 4, 9 };

            // We can access the elements too of course.
            // Let's change that errant '4' above.
            multi[1][2] = 9;

            // Let's iterate over it.
            foreach (int[] subarray in multi)
            {
                foreach (int element in subarray)
                {
                    Console.Write(element + " ");
                }

                // Blank line ...
                Console.WriteLine();
            }


            // Wait for a keypress
            Console.ReadKey();

            return 0;
        }
    }
}





1 3 4
9 9 9 9
0 4 6 3




.... and of course you can mix up child and parent objects in your arrays.

Arrays of Objects



In fact, since all classes derive from the object class (an alias for System.Object), you can even declare arrays that hold objects and put basically whatever the hell you like into them. Just do whatever you feel. Actually seriously, try to avoid doing this unnecessarily. I don't want to get all 1950s on your, but types are there for a reason. They help keep your code straight.

object[] stuff = { "hello", 4, true, 5.4 };

foreach(object obj in stuff)
{
    Console.WriteLine(obj);
}




hello
4
True
5,4