Why define this
int[] array = new int[] { 1, 2, 3 };
When you can define like this?
int[] array = {1, 2, 3};
Any thoughts?
Why define this
int[] array = new int[] { 1, 2, 3 };
When you can define like this?
int[] array = {1, 2, 3};
Any thoughts?
Feel like taking risk to answer that but..
From $12.6 Array initializers in C# 5.0 Language Spec;
The context in which an array initializer is used determines the type of the array being initialized. In an array creation expression, the array type immediately precedes the initializer, or is inferred from the expressions in the array initializer. In a field or variable declaration, the array type is the type of the field or variable being declared. When an array initializer is used in a field or variable declaration, such as:
int[] a = {0, 2, 4, 6, 8};
it is simply shorthand for an equivalent array creation expression:
int[] a = new int[] {0, 2, 4, 6, 8};
As other says, this can be called a syntactic sugar for this initializers.
But why?! Why does the creator of c# needs to have this "Syntactic sugar"?
Wikipedia page states this as well.
In computer science, syntactic sugar is syntax within a programming language that is designed to make things easier to read or to express. It makes the language "sweeter" for human use: things can be expressed more clearly, more concisely, or in an alternative style that some may prefer.
So, what is the proper method? Well, that question is subjective. Some may prefer first, some may prefer second, or even some may prefer var array = new[] { 1, 2, 3 };
based on your example. var
is also a syntactic sugar which comes C# 3.0 version. But with this, you can not write var array = { 1, 2, 3 };
since it can complicate the parser as Eric Lippert noted.
By the way, you can find All possible C# array initialization syntaxes in here and What is the difference between “Syntax” and “Syntactic Sugar” in Programming.SE.
Also I have to write this lovely comment by Anthony Pegram in Programming.SE;
In the end, it's all just syntatic sugar over electricity.