What is this new[] a shorthand for?

前端 未结 4 691
一整个雨季
一整个雨季 2020-12-07 02:35

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[] {
          


        
相关标签:
4条回答
  • 2020-12-07 02:41

    The notation is an implicitly typed array declaration.

    In your case, it is a array of object arrays.

    0 讨论(0)
  • 2020-12-07 02:49

    It's implicit typing. Since all the elements in that collection are object arrays, the compiler can deduce that the array itself must be a collection of object arrays.

    0 讨论(0)
  • 2020-12-07 02:59

    It means that new[] is an implicitly typed array. Since it's implicitly typed, you have to assign something to it as in this example. Just as you have to with the var keyword.

    0 讨论(0)
  • 2020-12-07 03:02

    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" }
       }
    };
    
    0 讨论(0)
提交回复
热议问题