Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to reinitialize an array?

Tags:

arrays

c#

So I have this array initialized:

string[] names = { "Joe", "Bob", "", "", "Marcus", "" };

Now I want to change the contents in a similar manner. I tried:

names = {"Happy", "", "", "Go", "", "Lucky"};

but this results in the error,

Only assignment, call, increment, decrement, and new object expressions can be used as a statement

Is there a way to bulk-assign the contents of an array like I am trying to do?

like image 631
merkaba48 Avatar asked Sep 02 '26 10:09

merkaba48


1 Answers

The raw { ... } syntax can only be used when declaring the array.

To create a new array instance, use new string[] { ... }. You can then assign this new array instance to the variable:

names = new string[] {"Happy", "", "", "Go", "", "Lucky"};

Note that the old array instance will not be affected.

like image 148
SLaks Avatar answered Sep 03 '26 23:09

SLaks



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!