3

I know the title might not be clear and I apologize about that. so I have 2 forms in visual studio and in the first form user logs in to the system and the second form is where everything else happens.

I have called a class called info in the first form, and the class is responsible to gather user info and check for login etc. when a user logs into the system, the class takes the user ID and stores it into a private string. and from there the program goes into the second form.

now here is my question, how can I make this class global so I can access the stored userID from the second form? can I just create another instance of the class (info myinfo = new info()) ?

PS I am new to object oriented concept so Please user easy terms.

John Saunders
  • 160,644
  • 26
  • 247
  • 397
Ahoura Ghotbi
  • 2,866
  • 12
  • 36
  • 65

2 Answers2

5

Personally, I would vote against globals. Instead, I usually do it the following way:

In the code that calls form 1, fetch the parameter from the form through a property. Pass it then to the second form through a parameter on the second form.

E.g.:

void Main()
{
    var form1 = new Form1();
    form1.ShowDialog();

    var info = form1.GetInfo();

    var form2 = new Form2();
    form2.SetInfo( info );
    form2.ShowDialog();
}

If you really insist on having a global class, please look at the Singleton pattern, as wsanville pointed out. Basically it would roughly look like:

public sealed class Info
{
    private static Info _instance;
    private static readonly object _lock = new object();

    // Private to disallow instantiation.
    private Info()
    {
    }

    public static Info Instance
    {
        get
        {
            lock (_lock)
            {
                if (_instance==null)
                {
                    _instance = new Info();
                }
                return _instance;
            }
        }
    }
}
Community
  • 1
  • 1
Uwe Keim
  • 39,551
  • 56
  • 175
  • 291
2

You can use the Singleton pattern to access one instance of your class throughout your application. For an implementation in C#, see Jon Skeet's article on the subject.

wsanville
  • 37,158
  • 8
  • 76
  • 101