Reputation: 81
I am writing a simple foreach loop to read key values from appconfig file. For some reason the array string called server looses previous values each time the foreach loop increments. Once the program runs to completion I see values as (server[0] = null, server[1]=null, server[2] = ). Only the last array pointer server[3] retains the values.
My questions are:
How can I retain all the array values and pass them outside the foreach loop?
private void button2_Click(object sender, EventArgs e)
{
int i = 0;
int max = 0;
string[] server;
foreach (string key in System.Configuration.ConfigurationManager.AppSettings)
{
max = max + 1;
}
foreach (string key in System.Configuration.ConfigurationManager.AppSettings)
{
server = new string[max];
server[i] = key;
MessageBox.Show(server[i]).ToString();
i = i + 1;
}
}
Upvotes: 1
Views: 2553
Reputation: 169008
What Evan said -- also, consider using LINQ to make your code more readable, and avoid similar bugs:
var server = System.Configuration.ConfigurationManager.AppSettings
.Cast<string>().ToList();
foreach (string key in server)
MessageBox.Show(key);
Upvotes: 3
Reputation: 7489
Evan is exactly right. In addition to that, I recommend replacing the first foreach loop with
max = System.Configuration.ConfigurationManager.AppSettings.Count;
Upvotes: 0
Reputation: 55334
server = new string[max];
Should be outside the loop (in your case, between the two), otherwise you create a new array every iteration. This explains why the last value is correct, and the rest are empty.
Also, you can use ++
instead of i + 1
and max + 1
.
Upvotes: 11