3

How can I initialize an array of strings in ONE go AFTER I declare it, not at that moment.

Example of what I don't want because I am aware you can do it like this:

string[] array = new string[2]; // creates array of length 2, default values
string[] array = new string[] { "A", "B" }; // creates populated array of length 2
string[] array = { "A" , "B" }; // creates populated array of length 2

Nor do I want it like this, because on a very long array, it would be very tedious:

array[0] = "a";
array[1] = "b";

I want to declare it first:

string[] array = new string[2];

Then I want some code to happen:

Console.WriteLine("The array has been made, time to fill it up");

And finally fill that array up, I've already tried the following ways but none of them work:

array { "a","b"};
array[] { "a","b"};
array = {"a","b"};
array[] = { "a", "b" };

Thank you ahead of time.

2
  • 3
    string[] array; ........................ array = new [] { "A", "B" }; Commented Feb 21, 2018 at 17:45
  • @PatrickArtner Yes that also worked, thank you. Commented Feb 21, 2018 at 17:55

2 Answers 2

12

You can break declaration and initialization like:

string[] array;
Console.WriteLine("The array has been made, time to fill it up");
array = new[] {"a","b"};
Sign up to request clarification or add additional context in comments.

Comments

3

That's not how arrays really work, when you create one you have to populate it OR re-create one and override the old value, so what you want is kind of not possible, at least not with arrays.

What you can do is either use a List and AddRange or use what Patrick Artner suggested in the comment below your post.

1 Comment

I see what you mean, great input.

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.