Search code examples
c#class

Make a created class variable reachable anywhere


So I am very new to C# and I am trying to reach a Class variable that was created inside of a case loop. But it keep saying that the class variable doesn't exist. Is there a way to make it public so that everything inside of the Class can reach the Class Variable?

Here is the example from my code.

string input = Console.ReadLine();
switch (input)
{
     case "1":
         Account personalAccount = new Account(userName);
         personalAccount.createAccount();
         Console.WriteLine($"Welcome! {userName} Your balance is {personalAccount.balance}");
     break;

{
     case "2":
         Console.WriteLine($Your balance is {personalAccount.balance}");
     break;
}

I am trying to access the Class variable that was created inside of case "1", from case "2".

I tried to create the variable in the beginning of the program, and then just fill it in when it was time to create the Class Variable.

I also tried googling, but it was hard to show the difference between Class and Class Variable, hopefully this code snipped helped making sense of my sistuation.


Solution

  • Visibility of variable is limited to scope.

    In your case the scope is the case block, only this one. So the variable is available only there.

    In order to access this variable from other scope (the other case) you need to define it in some enclosing scope, for example just before switch:

    string input = Console.ReadLine();
    Account personalAccount = null;
    switch (input)
    {
        case "1":
             personalAccount = new Account(userName);
             // ...
             break;
        case "2":
             Console.WriteLine($"Your balance is {personalAccount?.balance}"); // Don't forget to check if personalAccount is null!
             // ...
             break;
        //...
    }