I can not understand the difference between the declaration with array initialization in the first case and the second
int[] array = new int[3] { 1, 2, 3 };
int[] secondArray = { 1, 2, 3 };
They seem to do the same thing, maybe they work differently?
CodePudding user response:
There is no difference in the compiled code between the two lines.
CodePudding user response:
The second one is just a shortcut. Both statements have the same result. The shorter variant just wasn't available in early versions of C#.
CodePudding user response:
The first one uses 3 as a array size explictly, the 2nd one size is inferred. This might be work if you dont want to initialize the values.
CodePudding user response:
There is no difference between this two array initialization syntaxes in terms how they will be translated by the compiler into IL (you can play with it at sharplab.io) and it is the same as the following one:
int[] thirdArray = new int[] { 1, 2, 3 };
The only difference comes when you are using those with already declared variable, i.e. you can use 1st and 3rd to assign new value to existing array variable but not the second one:
int[] arr;
arr = new int[3] { 1, 2, 3 }; // works
// arr = { 1, 2, 3 }; // won't compile
arr = new int[] { 1, 2, 3 }; // works