Example: Singleton Pattern in C#

Pattern Type: Creational

A Singleton is generally used where you only ever want a single instance of a particular object to exist during the lifetime of your application, this is quite useful if you have a library of common access functions which you dont want people to keep instancing.

In the final parts of this article i will assume that you are familiar with generics, if not please go and read up on this subject first.

Okay, so last week i went over the Abstract Factory pattern, this week I’m covering the Singleton. Its called a ‘Singleton’ because its a single instance class and is generally only created when accessed.

So whats a very basic example of a singleton look like. The sxample below is an example of a singleton in its most basic form. The class is only created when the GetInstance public property is accessed but this version of the singleton has a problem, its not thread safe.

    public sealed class SimpleSingletonExample
    {
        static SimpleSingletonExample _instance = null;
        SimpleSingletonExample(){}

        public static SimpleSingletonExample GetInstance{
            get{
                if (_instance == null){
                    _instance = new SimpleSingletonExample();
                }
                return _instance;
            }
        }
    }

So what do we need to do to make this threadsafe, the solution is quite simple see the code listing below.

   public sealed class SimpleSingletonExample{
        private static volatile SimpleSingletonExample _instance;
        private static object  MakeThreadSafe = new Object();

        private SimpleSingletonExample() { }

        public static SimpleSingletonExample GetInstance
        {
            get{
                if (_instance== null){
                    lock (MakeThreadSafe){
                            _instance = new SimpleSingletonExample();
                    }
                }

                return _instance;
            }
        }
    }

So what have we dont to make this threadsafe? Firstly, i have altered the _instance field so that it now has the Volitile keyword meaning that the assignment must be complete before it can be accessed. Secondly, i have added the following private field to the class

           private static object MakeThreadSafe = new Object();

This private object will then be used to determine if an instance already exists, If you look in the GetInstance property you will see that the lock() keyword is used prevent access by other threads if an instance has already been created. In either example the Singleton object can be created by using the following syntax:

  SimpleSingletonExample myObject = SimpleSingletonExample.GetInstance;

But is it possible to make this kind of thing generic so that you can effectivly make any class a singleton!! The answer is ‘Yes’, so how do we mange this? well, the following code should demonstrate how this. Basically, we are using the power that Generics give us to allow us to extend an existing class by deriving from the SingletonObject.

    public class SingletonObject<T> where T : class, new()
    {
        static volatile T _instance;
        static Object EnsureThreadSafe = new Object();
        static SingletonObject() { }

        public static T GetInstance {
            get {
                if (_instance == null){
                    lock (EnsureThreadSafe){
                        _instance = new T();
                    }
                }
                return _instance;
            }
        }
    }

So lets create a simple class

    class testing{
        public testing(){ }

        public void testing123(){
            Console.Write("created");
        }
    }

Now, we want to use this as a singleton, so we can now derive from the SingletonObject that we had previously created.

    class testing : SingletonClass<testing>{
        public testing(){ }

        public void testing123(){
            Console.Write("created");
        }
    }

We can then create an instance of our class by doing the following

  testing x = testing.GetInstance;
  x.testing123();

3 Comments

  1. I see you don’t monetize your website, i know how to earn some extra money and get more visitors
    using one simple method, just search in google for: ideas by Loocijano

  2. Hey, I think your website might be having browser compatibility issues.
    When I look at your website in Chrome, it looks fine but when opening in Internet Explorer,
    it has some overlapping. I just wanted to
    give you a quick heads up! Other then that,
    excellent blog!

1 Trackback / Pingback

  1. The Dancing Lady, God Shiva In Nataraj Style, Buddha Statue Are Some Of The Examples Which We Took From Our Ancient Indian History. | uxinexon

Comments are closed.