Home > OS >  Call var users in another class c#
Call var users in another class c#

Time:05-12

I have a variable called var users=JsonConvert.DeserializedObject<User[]>(jsonResponse) this is located at Login.cs inside public class login.

So what I want to do is to call var users inside Menu.cs to be able to edit the same data in var users however I can't declare var users as public var users as this is not allowed. That's why I'm trying to find another way or workaround for this.

public class Login 
{
    public static string jsonResponse = File.ReadAllText("C:\\Users\\Admin\\C#_Activity 1\\Users.json");

    public static void LoginMenu()
    {
        var users = JsonConvert.DeserializeObject<User[]>(jsonResponse);
    }

}

public class Menu
{
     
    public static void BankMenu()
    {
        foreach (var user in users!)
        {
            Console.Writeline(user.FirstName); 
        }
    }
}
Users.json
[
  {
    "id": 1,
    "username": "sachin",
    "password": "sachin1",
    "firstName": "Sachin",
    "lastName": "Karnik",
    "birthdate": "2011-6-14",
    "balance": 20000,
    "cardNumber": 12345
  },
  {
    "id": 2,
    "username": "dina",
    "password": "dina1",
    "firstName": "Dina",
    "lastName": "Meyers",
    "birthdate": "2012-8-20",
    "balance": 20000,
    "cardNumber": 23456
  },
  {
    "id": 3,
    "username": "andy",
    "password": "andy1",
    "firstName": "Andy",
    "lastName": "Rose",
    "birthdate": "2010-2-11",
    "balance": 20000,
    "cardNumber": 34567
  }
]

CodePudding user response:

Make users the public static member instead of the jsonResponse. There is no reason to have the jsonReponse as a public member as far as I can tell. Something like this:

public class Login 
{
    public static User[] Users { get; private set;}

    public static void LoginMenu()
    {
        var json = File.ReadAllText("C:\\Users\\Admin\\C#_Activity 1\\Users.json");
        Users = JsonConvert.DeserializeObject<User[]>(json);
    }
}
  • Related