-2

When we login I want to use the EmployeeId in different windows. What is a good solution to do this?

So that after the login, the EmployeeId is a public int for all windows.

We use SQL Server for the login.

jarlh
  • 42,561
  • 8
  • 45
  • 63
  • 3
    Possible duplicate of [C# Global Variables](https://stackoverflow.com/questions/14368129/c-sharp-global-variables) – mjwills Nov 15 '18 at 11:16

2 Answers2

1

Presuming the application is WinForms or WPF then:

class Program
{
    public static int EmployeeId {get;set;}

}

class OtherWindow
{
    void Function()
    {
       int employeeId = Program.EmployeeId;

    }
}

If your app is a web server or other 'multi-user' system, then you will need to find a different way.

Neil
  • 11,059
  • 3
  • 31
  • 56
0

Why not? If you want to see EmployeeId as if it's a global variable you can implement a routine like below. But ensure EmployeeId being thread safe:

namespace MyNameSpace {
  ...
  public static class MyEnvironmentVariables {
    // Lazy<int> - let EmployerId be thread safe (and lazy)
    private static Lazy<int> GetEmployeeId = new Lazy<int>(() => {
      //TODO: implement it
      return ObtainEmployeeIdFromDataBase();
    });

    public static int EmployeeId {
      get {
        return GetEmployeeId.Value;
      }
    }
  }

then with a help of using static you can see it as if you have a global variable:

  // static: we don't want to mention pesky MyEnvironmentVariables
  using static MyNameSpace.MyEnvironmentVariables;

  ...
  public class MyDifferentWindow {
    ...
    public void MyMethod() {
      // we can use EmployerId as if it's a global variable
      int id = EmployeeId;
      ... 
Dmitry Bychenko
  • 180,369
  • 20
  • 160
  • 215