Initializing c# array with new vs. initializing with literal Initializing c# array with new vs. initializing with literal arrays arrays

Initializing c# array with new vs. initializing with literal


The second is array initializer syntax. It's just syntactic sugar. Both initialize new array instances with their respective values, the first being more explicit (you repeat that it is an integer array of two elements on the right hand side which is pretty obvious from what follows so the compiler is capable of inferring this information).

So the following are equivalent:

int[] array = new int[2] { 1, 2 };

and:

int[] array = { 1, 2 };

and:

var array = new[] { 1, 2 };

In all cases we are initializing an array of two integers. Personally I prefer the last syntax.


Arrays are reference types and are allocated using the C# new keyword as are other reference types.

One of your array syntaxes is simply a shorter syntax also recognized by the C# compiler - (there are other variations on it too) Both your examples allocate (new) and initialize {elements} for an array instance:

The first version explicitly states the size of the array.

int[] intarray = new int[2]{1,2};

The second version lets the C# compiler infer the size of the array by # of elements in the initialization list.

int[] intarray2 = {4,5,6};

In general the C# compiler recognizes specialized syntax for declaring and initializing C# native arrays masking the fact the underlying System.Array class is being used.


int[] intarray2 = {4,5,6};

is exactly the same than:

int[] intarray2 = new int[] {4, 5, 6};

is just a shorter (abbreviated) form of coding, in fact the compiler WILL allocate the memory the same qty of memory for the array, the first one is not explicitly write the "new", just like when you assign an integer to a double variable, you can write the cast or not (because is a safe cast), and will produce the same effect. example:

int i = 12;double d = i;

the same as:

int i = 12;double d = (double)i;