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
6
  • 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 ;. Commented Sep 3, 2014 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"}; Commented Sep 3, 2014 at 10:49
  • Only the language designers will know for sure why C# doesn't support the array initialisation syntax for array assignment. Commented Sep 3, 2014 at 10:51
  • @Franck it doesn't make sense. Both code will allocate array on heap. I mean, "string[] strArray;" is null by default. Commented Sep 3, 2014 at 10:53
  • Related : stackoverflow.com/a/7354144/2530848 Commented Sep 3, 2014 at 11:09

1 Answer 1

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"};
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.