Click here to Skip to main content
13,355,335 members (72,503 online)
Click here to Skip to main content
Add your own
alternative version


7 bookmarked
Posted 29 Sep 2011

common Singleton Pattern implementation using Generic

, 18 Oct 2011
Rate this:
Please Sign up or sign in to vote.
Customized implementation of the Singleton pattern using Generics.
I read this link content(Jon Skeet) and implement the singleton pattern in a class that can be used for any object that you want to be singleton.[^]

Generic implementation of Jon Skeet's is here:
public class Singleton<T> where T : new()
    private static readonly Lazy<T> lazy = new Lazy<T>(() => new T());


    public static T Instance
            return lazy.Value;

For example, we have a service:

public class SampleService
    public List<MyItemType> GetItems()
        var dataList = new List<MyItemType>();
        //do some works and fill dataList
        return dataList;

Everywhere I want to use SampleService, I can get a singleton instance in this way:

var serviceInstance = Singleton<sampleservice>.Instance;

var myList = serviceInstance.GetItems();


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


About the Author

omid rezaei hanjani
Software Developer
Iran (Islamic Republic of) Iran (Islamic Republic of)
No Biography provided

You may also be interested in...


Comments and Discussions

GeneralReason for my vote of 4 good Pin
Jai Mallesh10-Oct-11 20:38
memberJai Mallesh10-Oct-11 20:38 
GeneralProbably needs to be tagged as .Net 4 as it is using <code>L... Pin
Reiss5-Oct-11 4:30
memberReiss5-Oct-11 4:30 
GeneralRe: thanks reiss, now its be tagged as .Net 4 too Pin
omid rezaei hanjani18-Oct-11 0:42
memberomid rezaei hanjani18-Oct-11 0:42 
Generalthanks richard, I changed that Pin
omid rezaei hanjani4-Oct-11 23:01
memberomid rezaei hanjani4-Oct-11 23:01 
GeneralThis code is not fool proof. If I wish, I can directly creat... Pin
A. Rajesh Kumar3-Oct-11 21:21
memberA. Rajesh Kumar3-Oct-11 21:21 
GeneralReason for my vote of 2 The phrase "my implementation" impli... Pin
Richard Deeming3-Oct-11 10:59
memberRichard Deeming3-Oct-11 10:59 
GeneralRe: Thanks Richard, I changed "my implementation" to "generic im... Pin
omid rezaei hanjani5-Oct-11 0:51
memberomid rezaei hanjani5-Oct-11 0:51 

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
Web04 | 2.8.180111.1 | Last Updated 18 Oct 2011
Article Copyright 2011 by omid rezaei hanjani
Everything else Copyright © CodeProject, 1999-2018
Layout: fixed | fluid