Problem with unassigned local variable in c#
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:
开发者_JAVA技巧string[] value;
for (int i = 0; i < 3; i++)
{
value[i] = "";
}
Why it says that it's unassigned?
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);
}
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]="";
}
精彩评论