user332369 January 2017

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

Answers


Darin Dimitrov January 2017

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.


Juan Ignacio Cornet January 2017

Try this

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


Afnan Ahmad January 2017

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"

Post Status

Asked in January 2017
Viewed 3,236 times
Voted 11
Answered 3 times

Search




Leave an answer