"is this a valid, lazy, thread-safe singleton implementation for c#?" Code Answer

4

jon skeet has written an article about implementing the singleton pattern in c#.

the lazy implementation is version 5:

public sealed class singleton
{
    singleton()
    {
    }

    public static singleton instance
    {
        get
        {
            return nested.instance;
        }
    }

    class nested
    {
        // explicit static constructor to tell c# compiler
        // not to mark type as beforefieldinit
        static nested()
        {
        }

        internal static readonly singleton instance = new singleton();
    }
}

notice in particular that you have to explicitly declare a constructor even if it is empty in order to make it private.

By sync11 on February 28 2022

Answers related to “is this a valid, lazy, thread-safe singleton implementation for c#?”

Only authorized users can answer the Search term. Please sign in first, or register a free account.