Click here to Skip to main content
6,635,160 members and growing! (15,554 online)
Email Password   helpLost your password?
Languages » C# » Generics     Intermediate

Generic Singleton Provider

By davojc

An article describing how to use Generics to create a singleton provider.
C#.NET 2.0, WinXPVS2005, Dev
Posted:26 Jul 2005
Views:65,715
Bookmarked:41 times
Announcements
Loading...
 
Search    
Advanced Search
Add to IE Search
printPrint   add Share
      Discuss Discuss   Broken Article?Report  
18 votes for this article.
Popularity: 5.81 Rating: 4.63 out of 5

1
1 vote, 5.6%
2
1 vote, 5.6%
3
3 votes, 16.7%
4
13 votes, 72.2%
5

Introduction

Many people from different programming backgrounds should be familiar with the Singleton Pattern. Those who use it will find that they often have to write the same code each time they want to create a different Singleton class. With the advent of C# 2.0 Generics, it is possible to write this code only once.

Background

There are many articles about the Singleton Pattern. Probably the most comprehensive one for C# can be found here: "Implementing the Singleton Pattern in C#".

There is an increasing amount written about C# Generics. For example, a CodeProject article can be found here: "Generics in C# 2.0" by Ansil.

Using C# 2.0 Generics to achieve a reusable Singleton pattern

Using C# 2.0 Generics, it is possible to create what I have called a 'Singleton Provider'. This is a class that can be used repeatedly to instantiate a class as a singleton without having to re-write the singleton pattern code for that specific class. This has the added benefit of separating singleton code from the class code leaving the flexibility to use several instances of the class or using the class as a singleton.

The singleton code used in this example is based on the fifth example described in the above article about implementing the Singleton Pattern in C#:

    public sealed class Singleton
    {
        Singleton()
        {
        }

        public static Singleton Instance
        {
            get
            {
                return SingletonCreator.instance;
            }
        }
        
        class SingletonCreator
        {
            // Explicit static constructor to tell C# compiler

            // not to mark type as beforefieldinit

            static Nested()
            {
            }

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

With an understanding of Generics, you can see that there should be no reason to replace the type arguments in this block of code with the typical 'T' found in Generics. If this is done, the code looks like this.

    public class SingletonProvider <T> where T:new()
    {
        SingletonProvider() {}

        public static T Instance
        {
            get { return SingletonCreator.instance; }
        }

        class SingletonCreator
        {
            static SingletonCreator() { }

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

Note that the Generics must have a constraint on it. This constraint forces any type 'T' to have a default constructor, that is, a constructor that takes no parameters. This allows the SingletonCreator to instantiate the type 'T'.

So, how does one use the SingletonProvider? To understand how to use this, we need a test class. The test class has two features. The first is a default constructor that sets a timestamp member variable. The second is a public method that writes that timestamp using Debug.WriteLine. This setup means that no matter which thread uses this class in the Singleton Pattern, whenever that public method is called, it should output the same value.

    public class TestClass
    {
        private string _createdTimestamp;

        public TestClass ()
        {
            _createdTimestamp = DateTime.Now.ToString();
        }

        public void Write()
        {
            Debug.WriteLine(_createdTimestamp);
        }
    }

The class is used with the SingletonProvider as follows:

    SingletonProvider<TestClass>.Instance.Write();

Points of Interest

I have tested this code with a Dual Processor with hyper-threading enabled with 100 threads accessing the singleton. They all output the same value illustrating that this is a thread-safe generic way to create singletons.

I believe that this is a really neat illustration of how Generics can save you writing code.

History

This is the first iteration of this code, please provide any feedback as to whether you have used this or not or any problems that anyone has found with it!

License

This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here

About the Author

davojc


Member
I have been developing primarily with .NET for over 6 years now although I have previous experience with Java and C++.

Programming is very much only a work task. I rarely do anything programming related in my spare time.

And no, this isn't a recent picture Smile


Occupation: Web Developer
Location: United Kingdom United Kingdom

Other popular C# articles:

Article Top
You must Sign In to use this message board.
FAQ FAQ 
 
Noise Tolerance  Layout  Per page   
 Msgs 1 to 25 of 28 (Total in Forum: 28) (Refresh)FirstPrevNext
GeneralUsing this on Forms Pinmembernothinking6:24 2 Mar '07  
GeneralRe: Using this on Forms PinmemberAntonio David Gonzlez8:43 10 May '07  
AnswerRe: Using this on Forms PinmemberLusid Insanity10:41 14 May '07  
GeneralRe: Using this on Forms Pinmemberggeurts23:57 14 May '07  
GeneralRe: Using this on Forms Pinmembernothinking17:36 21 May '07  
AnswerRe: Using this on Forms Pinmemberggeurts6:47 22 May '07  
Questionusing SingletonProvider to create types on the fly PinmemberJonathan Karlen6:43 5 Feb '07  
AnswerRe: using SingletonProvider to create types on the fly Pinmembermercede22:12 18 Jul '08  
GeneralPointer to article where private on test class will prevent instantiation and force Singleton PinmemberWray Smallwood5:36 29 Nov '06  
QuestionThis way prevents a class being instantiated at all Pinmembercrellbar6:13 20 Apr '06  
AnswerRe: This way prevents a class being instantiated at all PinmemberStefan Prodan6:13 13 Nov '06  
AnswerRe: This way prevents a class being instantiated at all Pinmemberzapodlo15:45 24 Apr '07  
AnswerRe: This way prevents a class being instantiated at all Pinmemberradioman.lt@gmail.com21:51 2 Oct '07  
GeneralApp Domains Pinmembermonsteroftheid5:21 4 Aug '05  
Generalsingletoncreator PinmemberKeith Farmer10:33 26 Jul '05  
GeneralRe: singletoncreator Pinmemberdavojc0:10 27 Jul '05  
GeneralRe: singletoncreator PinmemberHarkos3:09 27 Jul '05  
GeneralRe: singletoncreator Pinmemberdavojc3:12 27 Jul '05  
GeneralRe: singletoncreator PinmemberRichard Deeming9:35 28 Jul '05  
GeneralRe: singletoncreator PinmemberGoran Mitrovic21:55 27 Jul '05  
GeneralRe: singletoncreator Pinmemberdavojc23:31 27 Jul '05  
GeneralInteresting PinmemberS. Senthil Kumar6:47 26 Jul '05  
GeneralRe: Interesting Pinmemberdavojc23:56 26 Jul '05  
GeneralRe: Interesting Pinmemberdavojc0:47 27 Jul '05  
GeneralRe: Interesting PinmembermSerg22:37 2 Aug '05  

General General    News News    Question Question    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

PermaLink | Privacy | Terms of Use
Last Updated: 26 Jul 2005
Editor: Smitha Vijayan
Copyright 2005 by davojc
Everything else Copyright © CodeProject, 1999-2009
Web21 | Advertise on the Code Project