简体   繁体   中英

having trouble with global variable

I looked all over the internet for solutions to this but none of them work:

public static void Main (string[] args)
{
    Console.Write ("What is your name: ");
    string input = Console.ReadLine ();

    sayHi ();
}

public static string sayHi() {
    Console.WriteLine ("Hello {0}!", input);
}

I don't need an answer that will help me do this without a global variable, that's not what I'm looking for

When I execute this I get this error:

The name 'input' does not exist in the current context

I tried making one of the lines

public string input = Console.ReadLine ();

but I get

Unexpected symbol 'public'

I tried

static string input = Console.ReadLine ();

But I get

Unexpected symbol 'static'

This

public static string input = Console.ReadLine ();

gives me

Unexpected symbol 'public'

I don't want a solution that doesn't use global variables

You should declare the variable outside of the Main method in the class containing both functions:

private static string input;

public static void Main (string[] args)
{
    Console.Write ("What is your name: ");
    input = Console.ReadLine ();

    sayHi ();
}

public static string sayHi() {
    Console.WriteLine ("Hello {0}!", input);
}

In this case the scope of the input variable will be the containing class and you can access it from all methods within this class.

There is no such thing as global variables in C#. This will do the trick for you. You could also try the static class with static members solution to simulate something like global variables, but that still won't be a global variable.

Try this (you're using an attribute in the class in this solution, it will be "global" inside this class)

public class YourClass{

    private static string _input;

    public static void Main (string[] args)
    {
        Console.Write ("What is your name: ");
        _input = Console.ReadLine ();

        sayHi ();
    }

    public static string sayHi() {
        Console.WriteLine ("Hello {0}!", _input);
    }
}

You can use Static class

static class Global
{
   private static string _gVariable1 = "";

   public static string Variable1
   {
      get { return _gVariable1 ; }
      set { _gVariable1 = value; }
   }
}

And you can use it like

Global.Variable1 = "any string value"

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM