Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using array initializer '{}' multiple times for the same variable doesn't compile

I am trying to compile following code in C#:

String[] words = {"Hello", "Worlds"};
words = {"Foo", "Bar"};

And I am getting compilation errors like:

Error 1 Invalid expression term '{'
Error 2 ; expected
Error 3 Invalid expression term ','

On the other hand if I try

String[] words = { "Hello", "Worlds" };
words = new String[] {"Foo", "Bar"};

It compiles fine. As per MSDN,

int[] a = {0, 2, 4, 6, 8};

it is simply a shorthand for an equivalent array creation expression:

int[] a = new int[] {0, 2, 4, 6, 8};

Why doesn't the first code sample compile?

like image 245
Babar Avatar asked Aug 04 '10 14:08

Babar


People also ask

How do you initialize an entire array with the same value?

Initializer List: To initialize an array in C with the same value, the naive way is to provide an initializer list. We use this with small arrays. int num[5] = {1, 1, 1, 1, 1}; This will initialize the num array with value 1 at all index.

What happens if an array initializer has more values than the size of the array?

But it's okay if the array is larger than the number of initializer values. When more elements are in the array than values in the initializer list, the computer automatically initializes the remaining or unmatched elements to zero.

Can we initialize array with variable in C?

The C99 standard allows variable sized arrays (see this). But, unlike the normal arrays, variable sized arrays cannot be initialized.

Which are the correct array initialization statements?

The initializer for an array is a comma-separated list of constant expressions enclosed in braces ( { } ). The initializer is preceded by an equal sign ( = ). You do not need to initialize all elements in an array.


2 Answers

Correct, the short initializer syntax is only allowed in a declaration. Not in a normal statement.

String[] words = new string[]{ "Hello", "Worlds" }; // full form
String[] words = { "Hello", "Worlds" };  // short hand, special rule
words = {"Foo", "Bar"};                  // not allowed
words = new String[] {"Foo", "Bar"};     // allowed, full form again

The short hand notation is only allowed when it used as (rhs) part of a declaration.

like image 147
Henk Holterman Avatar answered Oct 19 '22 23:10

Henk Holterman


C# spec 12.6 Array initializers

In a field or variable declaration, the array type is the type of the field or variable being declared. When an array initializer is used in a field or variable declaration, such as: int[] a = {0, 2, 4, 6, 8}; it is simply shorthand for an equivalent array creation expression: int[] a = new int[] {0, 2, 4, 6, 8};

String[] words = { "Hello", "Worlds" };

is a declaration but

words = {"Foo", "Bar"};

is not.

like image 29
desco Avatar answered Oct 19 '22 23:10

desco