-1

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.

A user
  • 94
  • 8
  • 3
    Please explain some more and display more code, it is very unclear from the question what you want to achieve. – OhmnioX Apr 16 '20 at 06:56
  • 1
    you definitly should read about variable scopes in c#, e.g. here: https://www.geeksforgeeks.org/scope-of-variables-in-c-sharp/ – MakePeaceGreatAgain Apr 16 '20 at 07:04
  • 1
    You don't need a global variable, you just need to declare `usrinput` in a scope where it's accessible in every place you plan to use it. I'd move the declaration before the foreach. As HimBromBeere said, you need to read up on scope. – Frauke Apr 16 '20 at 07:09

2 Answers2

1

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();
    }
}
0

it is not possible to create a true global variable in C#,

Static variable on a class. Done. Global in the definition of any global variable (i.e. you must be in the same process). And standard C#.

TomTom
  • 61,059
  • 10
  • 88
  • 148
  • I doubt that would help OP, as it´s really minimalstically written. In fact OP lacks the language-basics, how should he/she understand your answer? – MakePeaceGreatAgain Apr 16 '20 at 07:05
  • By looking up the terms in the C# langauge reference he should study. I would write a little more if it would not be so totally basic and fundamental. – TomTom Apr 16 '20 at 07:05