Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to run an instance of a class through out the application

Tags:

c#

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.

like image 931
Ahoura Ghotbi Avatar asked Nov 17 '25 05:11

Ahoura Ghotbi


2 Answers

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;
            }
        }
    }
}
like image 134
Uwe Keim Avatar answered Nov 19 '25 22:11

Uwe Keim


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.

like image 33
wsanville Avatar answered Nov 19 '25 20:11

wsanville