HomeSearch

C# Initialize Array

Initialize arrays with different syntax forms. Array initializer expressions are used.

Array, initialize.

An array can be initialized in several ways. With array initializer syntax, we can specify individual elements directly.Array

With special methods,

we can assign each element in an array to one value. This is often needed in programs. The syntax is important to review.

Array initializers.

An array initializer uses curly brackets with elements in comma-separated lists. The length (and number of dimensions) is inferred from the expression.

Here: We see an array initializer in a statement for a one-dimensional int[] array. The first 2 array initializers are equivalent.

So: They compile to the same instructions to populate the array. The "new int[]" syntax part is not required.

Next: The program creates a 2D array. The string[,] array (array5) creates a 2D array with two columns and two rows.

2D Array

Info: The lengths are inferred from the initializers. The number of dimensions, which are also called ranks, are also inferred.

C# program that uses array initializers using System; class Program { static void Main() { // We can declare arrays with curly brackets. // ... It is allowed to omit the type. int[] array1 = { 1, 2, 3 }; int[] array2 = new int[] { 1, 2, 3 }; // Use array initializations with strings. // ... We can specify two-dimensional arrays. // ... We can use empty arrays. string[] array3 = { "dot", "net", "perls" }; string[] array4 = new string[] { "DOT", "NET", "PERLS", null }; string[,] array5 = { { "dot", "perls" }, { "framework", "4.0" } }; string[] array6 = { }; // Print the length and ranks. Console.WriteLine("array1: {0} length", array1.Length); Console.WriteLine("array2: {0} length", array2.Length); Console.WriteLine("array3: {0} length", array3.Length); Console.WriteLine("array4: {0} length", array4.Length); Console.WriteLine("array5: {0} length, {1} rank", array5.Length, array5.Rank); Console.WriteLine("array6: {0} length, {1} rank", array6.Length, array6.Rank); } } Output array1: 3 length array2: 3 length array3: 3 length array4: 4 length array5: 4 length, 2 rank array6: 0 length, 1 rank

Discussion.

The C# language specification describes array initializers. We see that an array initializer is converted to a sequence of assignments into the newly-allocated arrays.

So: For this reason, performance of array initializers is equivalent in programs. The only difference is the source text.

Tip: Please see chapter 12 in The C# Programming Language Specification third edition.

Example, for-loop.

We can initialize arrays with for-loops, which overall may be best for your team because it uses the more standard style. We create a helper method for this purpose.

Static: We use two static methods, which save no state, and which receive strongly-typed arrays. The values they initialize are hard-coded.

Static Method

Tip: You can modify the methods to receive a second parameter, the value you want to initialize to. Extension methods could be used.

Extension
C# program that initializes arrays using System; class Program { static void Main() { // Initialize an array of -1 integers. int[] arr1 = new int[10]; InitIntArray(arr1); foreach (int i in arr1) { Console.Write(i); } Console.WriteLine(); // Initialize an array of space 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

Enumerable.Repeat.

Here we use Enumerable.Repeat to assign a new array to a single value series. We ensure the System.Linq namespace is included.

Tip: This style of code is often called list comprehension. We specify an entire array in a single declaration.

C# program that uses Enumerable using System; using System.Linq; class Program { static void Main() { // Initialize an array of -1 integers. int[] arr1 = Enumerable.Repeat(-1, 10).ToArray(); foreach (int i in arr1) { Console.Write(i); } Console.WriteLine(); // Initialize an array of space 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

Notes, for versus Enumerable.

Is the for-loop better? Each style of code suits different developers and teams. For my projects, I use the more standard loop style with for.

Enumerable.Range.

Here we use Enumerable.Range to initialize an array to an entire range of numbers or other values. This can be replaced with a loop. We include the System.Linq namespace.
C# program that uses Range using System; using System.Linq; class Program { static void Main() { // 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

Initialize, benchmark.

Here we benchmark Enumerable.Repeat. We find Enumerable to be much slower than a for-loop and direct allocation.

So: In other words, the first method is many times faster than the second method. This could be relevant in a program.

However: If it really doesn't matter, then the Enumerable.Repeat version might be better because it uses fewer lines of code.

Version 1: This code creates a new int array with 100 elements, and then initializes each element with a for-loop.

Int Array

Version 2: Here we call Enumerable.Repeat and then convert to an array with the ToArray extension method.

ToArray
C# program that benchmarks Enumerable.Repeat, ToArray using System; using System.Diagnostics; using System.Linq; class Program { const int _max = 1000000; static void Main() { // Version 1: initialize with for-loop. var s1 = Stopwatch.StartNew(); for (int i = 0; i < _max; i++) { int[] array = new int[100]; InitArray(array); } s1.Stop(); // Version 2: use Enumerable.Repeat. var s2 = Stopwatch.StartNew(); for (int i = 0; i < _max; i++) { int[] array = Enumerable.Repeat(-1, 100).ToArray(); } s2.Stop(); Console.WriteLine(((double)(s1.Elapsed.TotalMilliseconds * 1000000) / _max).ToString("0.00 ns")); Console.WriteLine(((double)(s2.Elapsed.TotalMilliseconds * 1000000) / _max).ToString("0.00 ns")); } static void InitArray(int[] array) { // Use for-loop. for (int i = 0; i < array.Length; i++) { array[i] = -1; } } } Output 64.97 ns for-loop 825.06 ns Enumerable.Repeat, ToArray

Array.CreateInstance.

With this method, we can create an array based on runtime parameters. So a method can create a string or int array (for example) based on its arguments.

Note: CreateInstance does not initialize the array to any special value (the default value is used). It only allocates (creates) the array.

Array.CreateInstance

A summary.

The C# compiler can understand and infer array creations. The dimensions and the length of the arrays is inferred from the initializers.

For repeat values,

we used methods and loops. You can fill an array with a single value, such as -1, or with a range of values. For smaller arrays, it is faster to use a for-loop.
Home
Dot Net Perls
© 2007-2019 Sam Allen. All rights reserved. Written by Sam Allen, info@dotnetperls.com.