3

I'm developing a winforms application which has a login and I'd like to keep track of the state (i.e. Logged In or Logged Out). I've seen other answers on SO like this one decrying the use of public or global variables like this:

public static bool LoggedIn;

private void btnLogin_Click(object sender, EventArgs e)
{
    //do some stuff
    LoggedIn = true;
}

So what is the best way to track a User State or other variables for a program? They should be accessible program wide. Thanks a lot!

Community
  • 1
  • 1
gnarlybracket
  • 1,691
  • 4
  • 18
  • 37
  • I think you should use an enum, to set and get the current state of the user. – Max Jan 22 '14 at 17:55
  • Please explain why you think you need a "public or global variable" to track this. Why would other classes care? What would happen if they were wrong? The class breaks? If that's the problem, fix your classes. If only a few classes need to know, pass the data to the class or make them `protected` or `internal`. – Dour High Arch Jan 22 '14 at 18:08
  • @DourHighArch I would like to know at all times if the user is logged in or out, and I need to access this information in different forms. The only way I know to do this is by creating a public variable and storing the information in there. – gnarlybracket Jan 22 '14 at 18:17

1 Answers1

1

That will work, but is seems to me as bad practice, a better practice is to use a singleton class, that will manage all the user functionality, just think if you are using threads and one thread is logging out and other is logging in and another one is trying to log something to db. Singleton is a thread safe pattern and will give you a lot of flexibility.

Liran
  • 591
  • 3
  • 13