Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is difference between these two array declarations?

Tags:

syntax

c#

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?

like image 970
Mouliyan Avatar asked Aug 01 '11 21:08

Mouliyan


People also ask

What is the two types of array declaration?

The declaration of an array involves defining the data types of the array elements as well as the number of elements to be stored in the array. A one-dimensional array stores elements sequentially. A two-dimensional array stores elements in rows and columns.

What is the difference between int a [] and int [] A?

Difference between “int[] a” and “int a[]” for Multidimensional Arrays in Java. For Multidimensional Arrays, in Java, there is no difference and any of the mentioned syntaxes can be used for declaration.

What is the difference between array definition and array declaration?

A definition of an identifier is a declaration for that identifier that: As you noted yourself the memory for the array is reserved in data section then you have a declaration of an array that at the same time is a definition. Save this answer.

What is difference between array initialization and declaration?

An array can be initialized at the time of its declaration. In this method of array declaration, the compiler will allocate an array of size equal to the number of the array elements. The following syntax can be used to declare and initialize an array at the same time. // initialize an array at the time of declaration.


1 Answers

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} );
like image 144
Jon Skeet Avatar answered Oct 19 '22 02:10

Jon Skeet