How To Create And Use a Singleton in C#?

Creating a Singleton is relatively simple. First we create a static variable _instance. In addition, we create a property Instance. We will use it later to access the Singleton. In addition, a new instance of the class is provided there, if none should exist yet. This way we also ensure that the singleton is initialized at exactly the right moment. Namely, only when we need it.

public class MyAwesomeClass
{
    private static MyAwesomeClass _instance;

    // Add other class properties here...

    public static MyAwesomeClass Instance
    {
        get {
            if (_instance == null) {
                _instance = new MyAwesomeClass();
            }

            return _instance;
        }
    }

    // Add other class methods here...

    public void SomeMethod()
    {
        Debug.Log("It works.");
    }
}

You can access the methods and properties of the Singleton like this:

MyAwesomeClass.Instance.SomeMethod();

There are no comments yet.