What is difference between these two array declarations?

前端 未结 5 1972
自闭症患者
自闭症患者 2021-01-11 21:05

It seems these two declarations are the same:

int[] array1 = {11, 22, 33};

and

int[] array2 = new int[] {11, 22, 33};


        
相关标签:
5条回答
  • 2021-01-11 21:31

    Since you are providing the initializer in the same line in which you are declaring, you cam omit the new operator.

    // This is OK

    int[] i32Array = { 1,2,3,4,5 };

    // This is NOT

    int[] i32Array; i32Array = { 1,2,3,4,5 };

    If your definition and initiation happens in different line you will have to do this

    i32Array = new int[] { 1,2,3,4,5 };

    So, technically speaking, it is possible to declare an array variable without initialization, but you must use the new operator when you assign an array to this variable

    0 讨论(0)
  • 2021-01-11 21:33

    The both are exactly the same

    look this code:

    int[] arr1={1,2,3,4};
    int[] arr2= new int[]{1,2,3,4};
    

    using the reflector the both converted to the following:

    int[] expr_07 = new int[]
                {
                    1, 
                    2, 
                    3, 
                    4
                };
                int[] expr_19 = new int[]
                {
                    1, 
                    2, 
                    3, 
                    4
                };
    
    0 讨论(0)
  • 2021-01-11 21:34

    Doesn't make a difference. They are both the same.

    0 讨论(0)
  • 2021-01-11 21:42

    There's no difference in this case - but the first syntax is only available when declaring a variable. From the C# 4 spec section 12.6:

    Array initializers may be specified in field declarations, local variable declarations, and array creation expressions.

    (The "array initializer" is the bit in braces - and an array creation expression is the form where you specify new int[] or whatever.)

    When you're not declaring a local variable or a field (e.g. if you're passing an argument to a method) you have to use the second form, or from C# 3.0 you can use an implicitly typed array:

    Foo(new[] { 1, 2, 3} );
    
    0 讨论(0)
  • 2021-01-11 21:45
    int[] array1; // declare array1 as an int array of any size
    array1 = new int[10];  // array1 is a 10-element array
    array1 = new int[20];  // now it's a 20-element array
    
    int[] array2 = new int[5] {1, 2, 3, 4, 5}; // declare array 2 as an int array of size 5
    

    Both are the same. See here at MSDN on initializing arrays.

    0 讨论(0)
提交回复
热议问题