The syntax of array creation expressions (ยง7.5.10.2) is extended to
support implicitly typed array creation expressions:
array-creation-expression: ... new [ ] array-initializer
In an implicitly typed array creation expression, the type of the
array instance is inferred from the elements specified in the array
initializer. Specifically, the set formed by the types of the
expressions in the array initializer must contain exactly one type to
which each type in the set is implicitly convertible, and if that type
is not the null type, an array of that type is created. If exactly one
type cannot be inferred, or if the inferred type is the null type, a
compile-time error occurs.
The following are examples of implicitly typed array creation
expressions:
var a = new[] { 1, 10, 100, 1000 }; // int[]
var b = new[] { 1, 1.5, 2, 2.5 }; // double[]
var c = new[] { "hello", null, "world" }; // string[]
var d = new[] { 1, "one", 2, "two" }; // Error
The last expression causes a compile-time error because neither int
nor string is implicitly convertible to the other. An explicitly typed
array creation expression must be used in this case, for example
specifying the type to be object[]. Alternatively, one of the elements
can be cast to a common base type, which would then become the
inferred element type.
Implicitly typed array creation expressions can be combined with
anonymous object initializers to create anonymously typed data
structures. For example:
var contacts = new[] {
new {
Name = "Chris Smith",
PhoneNumbers = new[] { "206-555-0101", "425-882-8080" }
},
new {
Name = "Bob Harris",
PhoneNumbers = new[] { "650-555-0199" }
}
};
Best Answer
They are not quite equivalent - at least not in the general case. The code using an object initializer is closer to this:
In other words, the assignment to the variable only occurs after the properties have been set. Now in the case where you're declaring a new local variable, that doesn't actually matter, and the compiler may well optimize to your first form. But logically, it does matter. Consider:
If that did the assignment to
p1
first, you'd end up with 0 for bothp1.x
andp1.y
. Whereas that's actually equivalent to:EDIT: I've just realised that you're using a struct rather than a class. That may make some subtle differences... but you almost certainly shouldn't be using a mutable struct to start with :)