How do I access a variable outside of an foreach (C#)

12,533

Solution 1

I cannot understand what do you want to achieve... but the code should be this:

 ArrayList lines = GetLines("test.txt", "8394", true);
 string result=string.Empty;       
 foreach (string s in lines)
        {
            result = s;
        }
        Console.WriteLine(result);

I think you want do to something like this:

 ArrayList lines = GetLines("test.txt", "8394", true);

 foreach (string s in lines)
        {
           Console.WriteLine(s);
        }

Solution 2

Your code is wrong logically. You loop through some lines, assign them to a variable, then do nothing to it, then assign the next line to a new variable (each time the loop gets another line, another variable called result is created), and so on.

This could be considered a logical code:

string names = string.Empty;
foreach (string name in namesList)
{
    names += ", " + name;
}
console.WriteLine(names);

Solution 3

Declare string result outside the foreach loop

string result = "" ;

foreach (string name in namesList)
{
    names += ", " + name;
}

....etc

Share:
12,533
Kraffs
Author by

Kraffs

Hi

Updated on June 04, 2022

Comments

  • Kraffs
    Kraffs almost 2 years

    I'm trying to get the variable result from a foreach in my main method. The code looks like this:

        static void Main(string[] args)
        {
    
            ArrayList lines = GetLines("test.txt", "8394", true);
            foreach (string s in lines)
            {
                string result = s;
            }
            Console.WriteLine(result);
        }
    

    As you can see it returns an error because I cannot access the variable outside of the foreach. How do I access it?