1

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:

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

3 Answers 3

11
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.

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks! I completely overlooked the issue.
3

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);

Comments

0

Evan is exactly right. In addition to that, I recommend replacing the first foreach loop with

max = System.Configuration.ConfigurationManager.AppSettings.Count;

Comments

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.