C# Initialize Array

Array

An array can be initialized in several ways. It can store 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.

For-loop

Start

To start, 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 to create a helper method for this purpose.

For
Based on:

.NET 4

C# program that initializes arrays

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

-1-1-1-1-1-1-1-1-1-1
Static

We use two static methods, which save no state, 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. This is worthwhile in larger programs.

Static MethodExtension Method

Enumerable.Repeat

To continue, we use the LINQ method Enumerable.Repeat to assign a new array to a single value series. We must ensure the System.Linq namespace is included. After this example, we will see Enumerable.Range.

C# program that uses Enumerable

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

-1-1-1-1-1-1-1-1-1-1
Question

Is the for-loop better? Not in all programs. Each style of code suits different developers and teams. For my projects, I would use the more standard loop style in the first example. It is more imperative and matches my style more.

List comprehension:The example that uses Enumerable.Repeat shows code that is called list comprehension.

Python:This is widely used in Python and other languages. It is elegant. But many developers prefer loops.

List, PythonPython

Enumerable.Range

Here we 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. We must include the System.Linq namespace.

C# program that uses Range

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

5
6
7
8
9

Benchmark

Performance optimization

Here we benchmark Enumerable.Repeat. Unfortunately, list comprehension in C# leaves a lot to be desired. I found Enumerable to be about 20 times slower than a for-loop and direct allocation.

So:In other words, the first example in this article is 20 times faster than equivalent code such as the second example.

Method used by benchmark: C#

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

Code benchmarked: C#

//
// 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

Initialize with for loop:            85 ms
Initialize with Enumerable.Repeat: 1645 ms

Summary

C# programming language

We saw examples of array initialization. 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 faster to use a for-loop, in the imperative style of coding.

Tip:This site has more information on initializing collections such as Lists, which are often more useful than arrays.

Initialize List

C#: Array