user2613018
user2613018

Reputation: 101

C# public static dictionary

So I'm trying to make a publicly accessible dictionary for my entire program to access, I created that under my Form as such:

public static Dictionary<string, int> categories = new Dictionary<string, int>
    {
    {"services", 0},
    {"files", 0},
    {"shortcuts", 0},
    {"registry", 0},
    {"browsers", 0}
    };

Now, inside of a private method, I have this code:

                foreach (KeyValuePair<string, int> reference in categories)
            {
                for (int i = 0; i < scanLines.Count; i++)
                {
                    if (scanLines[i].Contains(reference.Key))
                    {
                        start = i + 1;
                        break;
                    }
                }
                for (int i = start; i < scanLines.Count; i++)
                {
                    if (scanLines[i].Contains("*"))
                    {
                        stop = i - 1;
                        break;
                    }
                }
                // Write the result for the category by subtracting the difference between
                // the start and stop variables
                categories[reference.Key] = stop - start;

This is basically breaking up a log file in sections to count the lines in between those sections declared in the category dictionary. Now my problem is the line of code

categories[reference.Key] = stop - start;

keeps throwing an Invalid Operation Exception Error. What am I doing wrong here?

Upvotes: 3

Views: 5631

Answers (2)

irotaev
irotaev

Reputation: 69

You try to change csope-closed varible (categories) in foreach loop. It is unavalible operation.

It is simply to understand, as if you are allowed to change varible can be stored in out-of-memory stack.

Use anouther varible, as example, to make this operation.

Upvotes: -1

Ulugbek Umirov
Ulugbek Umirov

Reputation: 12797

You cannot change collection (and Dictionary is collection too) inside foreach loop for it. You can do quick workaround by creating duplicate collection as follows:

foreach (KeyValuePair<string, int> reference in categories.ToList())

Upvotes: 5

Related Questions