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?
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.
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.
The C99 standard allows variable sized arrays (see this). But, unlike the normal arrays, variable sized arrays cannot be initialized.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With