简体   繁体   中英

What is difference between these two array declarations?

It seems these two declarations are the same:

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

and

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

But what is the need of this part new int[] in the second sample?
Does it make difference?

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 (eg 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} );

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

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 .

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

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
            };

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM