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:
- Why does the server[0] and server[1] become null.
-
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; } }
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 ofi + 1andmax + 1.