-2

I was reading about Singleton design pattern when i come across this implementation:

public class Singleton
{
    private static Singleton Instance { get; private set; }

    private Singleton()
    {
    }

    static Singleton()
    {
        Instance = new Singleton();
    }
}

Is this singleton thread safe? What are pros and cons of such implementation?

3
  • For discussion of pros/cons (which are mostly off-topic on Stack Overflow), see e.g. csharpindepth.com/Articles/General/Singleton.aspx Commented Feb 15, 2017 at 19:26
  • I saw that article, but the above example was not mentioned Commented Feb 15, 2017 at 19:34
  • Your example is functionally identical to simply initializing the backing field directly, e.g. static Singleton Instance { get; } = new Singleton();, a variation that is discussed in the article. Of course, the code you posted is useless, because the Instance property is private, and so can only be called by the Singleton class itself (which has no constraints on how many instances of Singleton it can create...singletons are really only useful constructs for outside code). Commented Feb 15, 2017 at 19:36

1 Answer 1

0

No singletons are not thread safe, I would recommend reading https://msdn.microsoft.com/en-us/library/ff650316.aspx

Sign up to request clarification or add additional context in comments.

1 Comment

The singleton initialization the OP is asking about is thread-safe. Of course, whether the singleton object itself is thread-safe is a completely separate matter. Though, it'd be very bad form to write a singleton object that isn't thread-safe in a context where thread-safety is in any way an issue, since by its very nature, a singleton is used repeatedly and potentially concurrently.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.