Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is this new[] a shorthand for?

I can't seem to find any documentation on what new[] is supposed to be. From the example below it seems to be an object array shorthand

var json = new[] {
            new object[] {"20-Jun-2008", 200 },
            new object[] {"20-Jun-2009", 250 }
        };
like image 205
chobo Avatar asked Jan 29 '12 20:01

chobo


1 Answers

These are implicitly typed arrays.

See C# 3.0 specifications.

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" }
   }
};
like image 179
ken2k Avatar answered Oct 28 '22 20:10

ken2k