Saturday, January 30, 2010

Implicitly Typed Arrays

The syntax of array creation expressions (§ is extended to support implicitly typed array creation expressions:
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" }

1 comment: