1

Ok, i feel so ashamed to ask this question, but I can't understand why this code in c# does not compile in vs2010 express:

string[] value;
for (int i = 0; i < 3; i++)
        {
            value[i] = "";
        }

Why it says that it's unassigned?

2 Answers 2

5

you need to assign the array first, then items in the array.

 string[] value = new string[3];

If you want to add items dynamically, and have it resize as needed, you might be better off with a generic list, eg.

var values = new List<string>();
for(int i = 0; i < 3; i++)
{
    values.Add("");   // or values.Add(String.Empty);
}
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks! I forgot how to do it :(
2

Chris's already answered, and i'd like to add that you'd typically want to do the following:

string[] value = new string[3];
for (int i=0; i<value.Length; i++)
{
   value[i]="";
}

2 Comments

+1! Thanks also! Actually I do this: string[] value = new string[maxarray]; for (int i = 0; i < maxarray; i++)
To elaborate why this should be done: 1) using value.Length is clearer then some hardcoded value (or another variable which should hold the length (but might not at a later time due to code changes). 2) I'm not sure if that's still the case, but last time I checked the JIT was much better optimizing this code when the variable is checked against value.Length instead of some other argument. This is/was because this was recognized as a pattern where the variable couldn't be out of range for the array, so the array accesses need no range checking.

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.