1

I know this is a simple concept, but I need some help. I'm creating a winforms app, in c#, and I'm trying to organize my code. The first screen is a log in, and once the user is authenticated I return the users details. How/where should I store these details so that I don't have to retrieve them again each time I want to use them?

Thank you!

user948060
  • 953
  • 3
  • 12
  • 25

3 Answers3

3

Along the lines of what the others have said about the global static class, but with some sample code :

public class UserInfo
{
    private int userID;

    public int UserID
    {
        get { return userID; }
    }

    private string userName;

    public string UserName
    {
        get { return userName; }
    }

    public UserInfo(int userID, string userName)
    {
        this.userID = userID;
        this.userName = userName;
    }
}

public static class GlobalInfo
{
    private static UserInfo currentUser;

    public static UserInfo CurrentUser
    {
        get { return currentUser; }
        set { currentUser = value; }
    }
}

So, after the user has logged in, save the logged in info :

GlobalInfo.CurrentUser = new UserInfo(123, "Bob Jones");

When you need to fetch info :

UserInfo userInfo = GlobalInfo.CurrentUser;
Moe Sisko
  • 11,665
  • 8
  • 50
  • 80
1

You could create a global static class as answered in this question or look at a Singleton Pattern implementation

... or read this question "Global variable approach in C# Windows Forms application? (is public static class GlobalData the best)" for more options.

Community
  • 1
  • 1
brodie
  • 5,354
  • 4
  • 33
  • 28
0

I would go with a singleton as @brodie says, but implemented as an instance of the user details object pushed into a DI container. For example, Ninject supports binding to a instance via BindToConstant. So you would have your LoggedInUser instance (details of the logged in user) created when the user logs in, then Bind<LoggedInUser>.ToConstant(myLoggedInUser) (from memory). Then if you need to get the logged in user you would just pull the current instance from the DI container (via something like kernel.Get<LoggedInUser>()).

Rebecca Scott
  • 2,421
  • 2
  • 25
  • 39