C# Initialize Arrays

You want to initialize your C# array to a single value or series of values. Every element must be set to that value. This is helpful for lookup tables and interoperating with older systems. Here we see some array initialization tips, including examples and a benchmark of the methods, using the C# programming language.

=== Initialize array benchmarks in C# ===

Initialize with for loop:             85 ms  [much faster]
Initialize with Enumerable.Repeat:  1645 ms 

Using for loop to initialize array

Here we see that you can initialize arrays with for loops, which overall may be best for your team because it uses the more standard style. I show how you can create a helper method for this purpose.

=== Example program that initializes arrays (C#) ===

using System;

class Program
{
    static void Main()
    {
        // A
        // Initialize an array of -1 integers.
        int[] arr1 = new int[10];
        InitIntArray(arr1);
        foreach (int i in arr1)
        {
            Console.Write(i);
        }
        Console.WriteLine();

        // B
        // Initialize an array of ' ' chars.
        char[] arr2 = new char[5];
        InitCharArray(arr2);
        foreach (char c in arr2)
        {
            Console.Write(c);
        }
        Console.WriteLine();
    }

    /// <summary>
    /// Initialize array to -1
    /// </summary>
    static void InitIntArray(int[] arr)
    {
        for (int i = 0; i < arr.Length; i++)
        {
            arr[i] = -1;
        }
    }

    /// <summary>
    /// Initialize array to ' '
    /// </summary>
    static void InitCharArray(char[] arr)
    {
        for (int i = 0; i < arr.Length; i++)
        {
            arr[i] = ' ';
        }
    }
}

=== Output of the program ===

-1-1-1-1-1-1-1-1-1-1

Description. We use two static methods, which do not need to save state at the class level, and which receive strongly typed arrays. The values they initialize are hard-coded. You can modify the methods to receive a second parameter, the value you want to initialize to. Also, you could create extension methods to achieve more elegant syntax.

Using Enumerable.Repeat

Here we see that you can use the new LINQ method Enumerable.Repeat to assign a new array to a single value series. After this example, we will see Enumerable.Range.

=== Example program that uses Enumerable (C#) ===

using System;
using System.Linq;

class Program
{
    static void Main()
    {
        // A
        // Initialize an array of -1 integers.
        int[] arr1 = Enumerable.Repeat(-1, 10).ToArray();
        foreach (int i in arr1)
        {
            Console.Write(i);
        }
        Console.WriteLine();

        // B
        // Initialize an array of ' ' chars.
        char[] arr2 = Enumerable.Repeat(' ', 5).ToArray();
        foreach (char c in arr2)
        {
            Console.Write(c);
        }
        Console.WriteLine();
    }
}

=== Output of the program ===

-1-1-1-1-1-1-1-1-1-1

Is the for loop better?

Not always. Each style of code suits different developers and teams. For my projects, I would use the more standard loop style in the first example, simply because it is more imperative and matches my style more.

Note on Enumerable.Repeat. The example that uses Enumerable.Repeat shows code that is called list comprehension, which is widely used in Perl and Python among others. It is elegant, but many developers prefer loops.

Using Enumerable.Range

Here we see how you can use the LINQ method called Enumerable.Range to initialize an array to an entire range of numbers or other values. Again, this can be replaced with a loop.

=== Example program that uses Range (C#) ===

using System;
using System.Linq;

class Program
{
    static void Main()
    {
        // A
        // Initialize array of 5 sequential integers
        int[] arr1 = Enumerable.Range(5, 5).ToArray();
        foreach (int i in arr1)
        {
            Console.WriteLine(i);
        }
    }
}

=== Output of the program ===

5
6
7
8
9

Is Enumerable slower?

Yes. Unfortunately, list comprehension in C# leaves a lot to be desired, and I found Enumerable to be about 20x slower than a for loop and direct allocation. In other words, the first example in this article is 20x faster than equivalent code such as the second example.

=== Method used by benchmark ===

static void InitArray(int[] arr)
{
    //
    // Initialize array with for loop
    //
    for (int i = 0; i < arr.Length; i++)
    {
        arr[i] = -1;
    }
}

=== Code benchmarked ===

//
// 1
// Initialize with for loop
//
int[] arr = new int[100];
InitArray(arr);

//
// 2
// Initialize with LINQ
//
int[] arr = Enumerable.Repeat(-1, 100).ToArray();

=== Benchmark results ===
    For loop was faster.
    Enumerable.Repeat was much slower.
    See top for timings.

Summary

We saw several examples of array initialization in the C# programming language. You can fill an array with a single value, such as -1, or with a range of values. For smaller arrays, such as int[], it is a better performance choice to use a for loop, in the imperative style of coding. This site has more information on initializing collections such as Lists, which are more useful than arrays often.

See Initialize List.

See Array Overview.

© 2007-2010 Sam Allen. All rights reserved.

Dot Net Perls  Sam Allen