This creates a strongly typed monodimensional array "directly":
int[] array = new int[10];
Under the hood it uses the IL command newarr
.
This one is more similar to using reflection to create an array (the type can be decided at runtime)
int[] array2 = (int[])Array.CreateInstance(typeof(int), 10);
The array created in the end is the same but the speed of creating it is much slower when using Array.CreateInstance
. Note that with Array.CreateInstance
you can dynamically select the type of the array (in the same way that through reflection you can create an instance of a type given the type at runtime), for example:
Type type = someCondition ? typeof(int) : typeof(string);
Array array2 = Array.CreateInstance(type, 10);
Another big difference: the "base" Array
class is weakly typed (so its methods use object
parameters, instead of int
/string
'/something
). So:
int num = (int)array2.GetValue(1); // You have to cast the return value to int from object
Another reason to use
array[5] = 1;
instead of
array2.SetValue(5, 1);
is that the first method is optimized in the IL code as a direct access to a monodimensional array (stelem
and ldelem
). The same is true for GetValue
.
The reason I'm using the term "monodimensional array":
In .NET there are two "types" of arrays: the monodimensional arrays and the "complex" arrays (they can be multidimensional, or with the first element not at the 0 index, or both). The second group is much slower. The stelem
and ldelem
work only with monodimensional arrays. For multidimensional/special arrays "hidden" methods are used to access them (the C# compiler changes the get and set so that these methods are called) (they are similar to the GetValue
/SetValue
of the Array
class, see for example https://stackoverflow.com/a/597729/613130 )