0

In C#, what exactly is the reason for this syntax to work for an array initialization :

string[] strArray = {"foo1", "foo2"}; //works

but not for an assignment :

strArray = {"foo1", "foo2"}; //does not work, throws "; expected" exception
  • Side-note: the second works in VB.NET. In C# you need `strArray = new []{"foo1", "foo2"};`. I assume the reason is that `{` introduces a new scope with this invalid statement: `"foo1", "foo2"` which has no `;`. – Tim Schmelter Sep 03 '14 at 10:43
  • It doesn't work because array is a fix length size so can only be assigned completely on initialization or pointer per pointer `strArray[0] = "foo1";strArray[1] = "foo2";`. You are trying to assign the Array and not the pointer themselves on the second like,setting array required new initialization so `new []{"foo1", "foo2"};` – Franck Sep 03 '14 at 10:49
  • Only the language designers will know for sure why C# doesn't support the array initialisation syntax for array assignment. – Matthew Watson Sep 03 '14 at 10:51
  • @Franck it doesn't make sense. Both code will allocate array on heap. I mean, "string[] strArray;" is null by default. – Eldar Dordzhiev Sep 03 '14 at 10:53
  • Related : http://stackoverflow.com/a/7354144/2530848 – Sriram Sakthivel Sep 03 '14 at 11:09
  • I guess Sriram link and Tim and Matthew's answers all point to the fact that the c# designers were unhappy with the array initialisation syntax but kept it for compatibility reasons and did not want to encourage this use by allowing it elsewhere. I also agree with Eldar that the question of the array size is not completely relevant. Thank you all for your help. – Cheradenine Zakalwe Sep 03 '14 at 12:13

1 Answers1

0

You need to specifies the size of an array. When you mention items of an array exactly when you define it, the size of array will be defined automatically. But when you want to give it values later, you need to specify size of the array when you're creating it.

string[] strArray = new string[number]; //number is size of your array.

So in this way you can valuate this array whenever later you want.

strArray = {"foo1","foo2"};