DEV Community

Discussion on: Singleton Design Pattern in c#

Collapse
 
katnel20 profile image
Katie Nelson

Hey Patrick, nice post.
Have you tried using the Lazy class for thread safety?

public sealed class ThreadSafeSingleton
{
    private static readonly Lazy<ThreadSafeSingleton> lazy =
        new Lazy<ThreadSafeSingleton>(() => new ThreadSafeSingleton());

    public static ThreadSafeSingleton GetInstance() => lazy.Value;

    private ThreadSafeSingleton()
    {
    }
}

It looks to simplify things, but requires .NET 4 or higher.

Collapse
 
patzistar profile image
Patrick Schadler

Hi Katie,
no, I did not, but I will :).

Thank you for your reply.

Collapse
 
katnel20 profile image
Katie Nelson

I used it in one place so far. No issues found yet. Let me know how it works out for you.