65.9K
CodeProject is changing. Read more.
Home

Simple Singleton Pattern in C#

starIcon
emptyStarIcon
starIcon
emptyStarIconemptyStarIconemptyStarIcon

1.91/5 (5 votes)

Nov 1, 2011

CPOL
viewsIcon

11647

Make it a generic class and fix your problem forever. This works because the compiler turns the generic into a new class (something like SigletonManagerOfTypeParamterTypeName). So the static variables are not shared amongst instances...public static class Singleton where...

Make it a generic class and fix your problem forever. This works because the compiler turns the generic into a new class (something like SigletonManagerOfTypeParamterTypeName). So the static variables are not shared amongst instances...

public static class Singleton<TSingletonType>
    where TSingletonType: class, new()
{
    private static volatile TSingletonType instance;
    private static object syncRoot = new Object();

    public static TSingletonType Instance
    {
        get
        {
            if (instance == null)
            {
                lock (syncRoot)
                {
                    if (instance == null)
                        instance = new TSingletonType();
                }
            }

            return instance;
        }
    }
}

Usage (check it out, it works):

Form frm = Singleton<Form>.Instance;
Control ctrl = Singleton<control>.Instance;