I have a variable called users
it stores my defined dictionary and I want to call globally call users
to access all its values however when I try to use public static var users
I get an error saying it only applies locally.
var users
is located in Login.cs
and I want to pass it to Menu.cs
.
Login.cs
namespace Bank
{
public class Login
{
public static void LoginMenu()
{
var users = new Dictionary<int, User>()
{
{1, new User {UserName="sachin",Password="sachin1",FirstName="Sachin",LastName="Karnik",BirthDate= new DateTime(2011,6,14),Balance=20000,CardNumber=012345}},
{2, new User {UserName="dina",Password="dina1",FirstName="Dina",LastName="Meyers",BirthDate= new DateTime(2012,8,20),Balance=20000,CardNumber=023456}},
{3, new User {UserName="andy",Password="andy1",FirstName="Andy",LastName="Rose",BirthDate= new DateTime(2010,2,11),Balance=20000,CardNumber=034567}},
};
}
}
}
Menu.cs
namespace Bank
{
public class Menu
{
public static void BankMenu()
{
foreach(var i in Enumerable.Range(1,3)){
Console.Write(users[i].FirstName "\n");
}
}
}
}
CodePudding user response:
As @fredrik wrote, you have declare the variable inside the function so it won't be available outside of this function. Move the declaration to class scope.
You should also notice that var keywork may only appear within a local variable declaration.
You should write it as following:
Login.cs:
namespace Bank
{
public class Login
{
public static Dictionary<int, User> users;
public static void LoginMenu()
{
users = new Dictionary<int, User>(){
{1, new User {UserName="sachin",Password="sachin1",FirstName="Sachin",LastName="Karnik",BirthDate= new DateTime(2011,6,14),Balance=20000,CardNumber=012345}},
{2, new User {UserName="dina",Password="dina1",FirstName="Dina",LastName="Meyers",BirthDate= new DateTime(2012,8,20),Balance=20000,CardNumber=023456}},
{3, new User {UserName="andy",Password="andy1",FirstName="Andy",LastName="Rose",BirthDate= new DateTime(2010,2,11),Balance=20000,CardNumber=034567}},
};
}
}
}
Menu.cs
namespace Bank
{
public class Menu
{
public static void BankMenu()
{
foreach(var i in Enumerate.Range(1,3)){
Console.Write(Login.users[i].FirstName "\n");
}
}
}
}