Click here to Skip to main content
12,895,064 members (61,055 online)
Click here to Skip to main content
Add your own
alternative version


15 bookmarked
Posted 26 Dec 2012

Usage of singleton wrapper for better coding

, 24 Jan 2013 CPOL
Rate this:
Please Sign up or sign in to vote.
More advanced singleton implementation.


In this short tip I want to introduce to the community my implementation of a singleton wrapper. So let's begin.


Recently I discovered an article (link) which was written by Sir Schamese. In his post he shows his implementation of the singleton pattern. But this implementation lacks lazy initialization. So I decided to implements a singleton by myself.

Code implementation 

When .NET 4.0 was released many developers discovered a useful primitive type called Lazy<T>.

Besides lazy initialization capabilities, Lazy<T> has another use, which is related to thread-safety. Being a developer who has been doing multithreading almost each day, I noticed that class was very useful for myself.

We can use lazy initialization to defer the creation of a large or resource-intensive object, or the execution of a resource-intensive task, particularly when such a creation or execution might not occur during the lifetime of the program. 

So I'm going to show you my singleton wrapper which under the hood uses Lazy<T>.

public abstract class SingletonBase<T> where T : class
    private static readonly Lazy<T> _Lazy = new Lazy<T>(() =>
        // Get non-public constructors for T.
        var ctors = typeof(T).GetConstructors(System.Reflection.BindingFlags.Instance | 
        if (!Array.Exists(ctors, (ci) => ci.GetParameters().Length == 0))
            throw new InvalidOperationException("Non-public ctor() was not found."); 
        var ctor = Array.Find(ctors, (ci) => ci.GetParameters().Length == 0);
        // Invoke constructor and return resulting object.
        return ctor.Invoke(new object[] { }) as T;
    }, System.Threading.LazyThreadSafetyMode.ExecutionAndPublication);
    public static T Instance
            return _Lazy.Value;

So for making any class behavior like singleton, let's do this:

public class MySingleton: SingletonBase<MySingleton>
  private MySingleton(){ }

As a result our class called MySingleton will inherit singleton behavior.

Caution: An important moment, if you didn't provide any private ctor in your class, an InvalidOperationException will be thrown!!!

I strongly recommend you use lazy initialization in case your objects can be heavy in memory allocation (allocation of resources), or when you are sure that an object can not be used by a program for some reason.  

So what do we gain with such implementation ? 

  • thread safety
  • lazy initialization

Hope you will find this tip/trick helpful for yourself and you will use it in your projects. Happy coding for all of you


This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


About the Author

Oleksandr Kulchytskyi
Team Leader Delphi LLC
Ukraine Ukraine
No Biography provided

You may also be interested in...


Comments and Discussions

GeneralMy vote of 5 Pin
Klaus Luedenscheidt24-Jan-13 18:46
memberKlaus Luedenscheidt24-Jan-13 18:46 
GeneralRe: My vote of 5 Pin
Oleksandr Kulchytskyi24-Jan-13 21:08
memberOleksandr Kulchytskyi24-Jan-13 21:08 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.

Permalink | Advertise | Privacy | Terms of Use | Mobile
Web02 | 2.8.170424.1 | Last Updated 24 Jan 2013
Article Copyright 2012 by Oleksandr Kulchytskyi
Everything else Copyright © CodeProject, 1999-2017
Layout: fixed | fluid