In .NET, an array can be initialized in several ways. With array initializer syntax, we can specify individual elements directly.
We can assign each element in an array to one value. This is often needed in programs, and the syntax is important to review.
An array initializer uses curly brackets with elements in comma-separated lists. The length (and number of dimensions) is inferred from the expression.
int
arrays. The first 3 array initializers are equivalent.string
arrays with initializers. For array 7, we create a 2D array with 2 columns and 2 rows.Length
property, and the Rank property if two-dimensional.using System; // Part 1: declare arrays with curly brackets. // ... It is allowed to omit the type. int[] array1 = { 1, 2, 3 }; int[] array2 = new int[] { 1, 2, 3 }; int[] array3 = [1, 2, 3]; // Part 2: use array initializations with strings. // ... We can specify two-dimensional arrays. // ... We can use empty arrays. string[] array4 = { "dot", "net", "perls" }; string[] array5 = new string[] { "DOT", "NET", "PERLS", null }; string[] array6 = { }; string[,] array7 = { { "dot", "perls" }, { "framework", "4.0" } }; // Part 3: print the length and ranks. Console.WriteLine($"int {array1.Length} {array2.Length} {array3.Length}"); Console.WriteLine($"string {array4.Length} {array5.Length} {array6.Length}"); Console.WriteLine($" {array7.Length} / {array7.Rank}");int 3 3 3 string 3 4 0 4 / 2
for
-loopWe can initialize arrays with for
-loops, which (overall) may be best for a team—it uses the more standard style. We create a helper method for this purpose.
static
methods, which save no state, and which receive strongly-typed arrays. The values they initialize are hard-coded.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] = ' '; } } }-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.
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(); } }-1-1-1-1-1-1-1-1-1-1
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.
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); } } }5 6 7 8 9
Here we benchmark Enumerable.Repeat
. This method is elegant, but if it causes a performance loss, it may be necessary to avoid it in some programs.
int
array with 100 elements, and then initializes each element with a for
-loop.Enumerable.Repeat
and then convert to an array with the ToArray
extension method.Enumerable
is faster than a for
-loop and direct allocation.using System; using System.Diagnostics; using System.Linq; const int _max = 1000000; // Version 1: initialize with for-loop. var s1 = Stopwatch.StartNew(); for (int i = 0; i < _max; i++) { int[] array = new int[100]; for (int z = 0; z < array.Length; z++) { array[z] = -1; } } 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")); }52.89 ns for-loop 36.40 ns Enumerable.Repeat, ToArray
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.
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.
CreateInstance
does not initialize the array to any special value (the default value is used). It only allocates (creates) the array.The C# compiler can understand and infer array creations. The dimensions and the length of the arrays is inferred from the initializers.