Search code examples
c#operating-systemcosmos

How to replicate a global variable in C#?


I have a variable in one loop in C# that cannot be recognized in the other one, and I am aware that it is not possible to create a true global variable in C#, however I wonder if one can mimic one. Some of my code is this:

foreach (string line in lines)
{
    if (line.Contains("write"))
    {
        var tempctr = line.Replace("(", "");
        var tempctr2 = line.Replace(")", "");
        var ctr = tempctr2.Remove(0, 6);
        Console.Write(ctr);
    }
    else if (line.Contains("sayinput"))
    {
        Console.Write(usrinput);
    }
    else if (line.Contains("inputget"))
    {
        var tempctr = line.Replace("(", "");
        var tempctr2 = line.Replace(")", "");
        var ctr = tempctr2.Remove(0, 9);
        Console.Write(ctr);
        string usrinput = Console.ReadLine();
    }
}

The code reads from a text file and runs a certain command based on what is in the text. My intention is for it to create a variable with inputget and spit it back out with sayinput. And the first usrinput reference is an error, since the variable is declared outside of the loop.


Solution

  • You don't need a global variable here. Just declare usrinput outside your loop, like so:

    string usrinput = "";
    
    foreach (string line in lines)
    {
        if (line.Contains("write"))
        {
            //...
        }
        else if (line.Contains("sayinput"))
        {
            Console.Write(usrinput);
        }
        else if (line.Contains("inputget"))
        {
            // ...
            usrinput = Console.ReadLine();
        }
    }