Mouliyan
Mouliyan

Reputation: 470

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?

Upvotes: 9

Views: 437

Answers (5)

Mohammed Asaad
Mohammed Asaad

Reputation: 138

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

Upvotes: 1

BBC
BBC

Reputation: 211

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

Upvotes: 1

user195488
user195488

Reputation:

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.

Upvotes: 1

Jon Skeet
Jon Skeet

Reputation: 1503669

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

Upvotes: 11

Al W
Al W

Reputation: 7713

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

Upvotes: 2

Related Questions