Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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".

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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;
    //...
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading