graham23s
graham23s

Reputation: 385

Variable cannot be accessed below a certain point in the code

I have a small problem with a piece of code I cannot seem to work out what the issue is, I never wrote this initial part of the code which is why I don't understand the problem.

Code:

        public async Task GetEnumerableLinksAsync(string entryPointUrl)
        {
            Uri baseUrl = new Uri(entryPointUrl);
            await foreach (Uri url in GetEnumerableLinksAsync(baseUrl, 1000))
                ListBoxMain.Items.Add(url);
                // TEST
                string[] threads = File.ReadAllLines(@"logic\markers.txt");
                if (threads.Any(url.Contains)) { 
            
                }
                // TEST
        }

The problem is here if (threads.Any(url.Contains)) { I cannot access the url variable.

ListBoxMain.Items.Add(url); the listbox can access it fine, but any code below this and I get the name `url` does not exist in the current context

Can anyone see the issue at all? any help is appreciated.

Upvotes: 1

Views: 28

Answers (1)

Neil
Neil

Reputation: 11889

The code you have written looks correct because of indentation, but C# ignores any formatting.

This is your code formatted properly:

await foreach (Uri url in GetEnumerableLinksAsync(baseUrl, 1000))
    ListBoxMain.Items.Add(url);
// TEST
string[] threads = File.ReadAllLines(@"logic\markers.txt");
if (threads.Any(url.Contains)) { 
        
}
// TEST

Can you see the why url doesn't exist after the foreach now?

You need to add a 'scope' to the foreach to allow url to exist beyond the first line:

await foreach (Uri url in GetEnumerableLinksAsync(baseUrl, 1000))
{
    ListBoxMain.Items.Add(url);
    // TEST
    string[] threads = File.ReadAllLines(@"logic\markers.txt");
    if (threads.Any(url.Contains)) { 
        
    }
    // TEST
}

Two hints:

  • start using Ctrl+KD more often. This formats your code and would have shown the issue.
  • Always use braces when using compound functions, like if,else,foreach etc.

Upvotes: 3

Related Questions