user3501613
user3501613

Reputation: 610

Singleton Class in c#

I am trying to understand singleton pattern in C#. I got 1 structure for that but i have some doubt in the implementation. Since I'm new to C#, i want to know how this is working.

public class Class1
{
    public static void Main(string[] args)
    {      
        Singleton.Object.Func1();
    }
}

public sealed class Singleton
{
    private static readonly Singleton _obj = new Singleton();

    static Singleton() { } // Make sure it's truly lazy

    private Singleton() { } // Prevent instantiation outside

    public static Singleton Object { get { return _obj; } }

    public void Func1() { }
}
  1. Is this pattern correct for a singleton class?

  2. What is the purpose of this line "static Singleton() { } // Make sure it's truly lazy"

  3. How the class identify only 1 instance is created in a particular time

Upvotes: 0

Views: 152

Answers (2)

AdaRaider
AdaRaider

Reputation: 1146

  1. Yes this pattern is pretty much bare bones implementation of the singleton pattern.
  2. While not strictly necessary, the purpose of that line looks like it might be trying to teach you a bit about C#, since static constructors are not the same as regular constructors. https://learn.microsoft.com/en-us/dotnet/csharp/programming-guide/classes-and-structs/static-constructors

Note that:

A static constructor is called automatically to initialize the class before the first instance is created or any static members are referenced.

  1. The class achieves this by having a private constructor, which means that only code inside the class implementation could instantiate an instance.

The singleton pattern is commonly used when you only want one instance of your class to be created. For example you might want to have an InputManager class who deals will processing all of the mouse and keyboard events for your engine. It doesn't make sense to have multiple instances of this class because then you would have to keep multiple copies of the manager up to date and then determine whose job it is to process the event. Instead you can use a singleton to make sure that input is all dealt with by the one manager.

Upvotes: 1

Prodigle
Prodigle

Reputation: 1797

Your pattern is valid. There are some other ways to do it but this is fine.

static Singleton() { } I don't believe is necessary but I could be wrong, it's more akin to something you need to do in C++ to make sure when you call for it, it grabs the singleton.

As _obj is static, the class can only have 1 version of it at any given time, meaning whenever you call it with .Object, it returns this one valid copy.

Upvotes: 3

Related Questions