TheDeveloperBlog.com

Home | Contact Us

C-Sharp | Java | Python | Swift | GO | WPF | Ruby | Scala | F# | JavaScript | SQL | PHP | Angular | HTML

C# Initialize Array

These C# example programs initialize arrays with different syntax forms. Array initialization is benchmarked.

Initialize 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. 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.

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

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

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


Related Links

Adjectives Ado Ai Android Angular Antonyms Apache Articles Asp Autocad Automata Aws Azure Basic Binary Bitcoin Blockchain C Cassandra Change Coa Computer Control Cpp Create Creating C-Sharp Cyber Daa Data Dbms Deletion Devops Difference Discrete Es6 Ethical Examples Features Firebase Flutter Fs Git Go Hbase History Hive Hiveql How Html Idioms Insertion Installing Ios Java Joomla Js Kafka Kali Laravel Logical Machine Matlab Matrix Mongodb Mysql One Opencv Oracle Ordering Os Pandas Php Pig Pl Postgresql Powershell Prepositions Program Python React Ruby Scala Selecting Selenium Sentence Seo Sharepoint Software Spellings Spotting Spring Sql Sqlite Sqoop Svn Swift Synonyms Talend Testng Types Uml Unity Vbnet Verbal Webdriver What Wpf