Paulie
Paulie

Reputation: 7015

C# Global Variables for Instances of a class

I understand that questions about Global Variables in C# has been asked so many times, but if possible would anyone be able to explain how to use an instance of one class that's being created in one method, but also being needed in another method as I have to rely on one instance and not to create multiple instances. Other questions online haven't been of help of what I seen.

My code below:

    public void loadCreateAccountCtr()
    {
        // Create Controller
        CreateAccountController ctr = new CreateAccountController();
        // Start Controller
        ctr.start();
        // Session is active
    }

    public void checkCredentials(string appNum)
    {
        CreateAccountController ctr = new CreateAccountController();
        ctr.create();

    }

I'm creating an instance of the CreateAccountController 'ctr' so I can access the methods in the controller, when I am going to send data to another part of the system I need to call another method. How would I use the previous instance without creating a new instance (As seen in checkCredentials(...)

Thanks

Upvotes: 1

Views: 1293

Answers (2)

DDan
DDan

Reputation: 8276

What you are describing is the Singleton Design Pattern. Read about it and see examples here.

However ahmelsayed's answer solves your problem perfectly in this situation, if later you will have to access the same class from other classes in your system, implementing your CreateAccountController as Singleton would solve the problem globally. You can get back to this later. Good luck!

Upvotes: 3

ahmelsayed
ahmelsayed

Reputation: 7392

read about variable scopes in C# https://msdn.microsoft.com/en-us/library/aa691132(v=vs.71).aspx

private CreateAccountController ctr;
public void loadCreateAccountCtr()
{
    // Create Controller
    ctr = new CreateAccountController();
    // Start Controller
    ctr.start();
    // Session is active
}

public void checkCredentials(string appNum)
{
    if (ctr != null)
    {
        ctr.create();
    }
    else
    {
        //handle this case here
    }
}

Upvotes: 5

Related Questions