Home > DeveloperSection > Forums > How to implement singleton design pattern in C#?
Anupam Mishra

Total Post:135

Points:949
Posted on    January-26-2016 10:17 PM

 C# C#  .NET 
Ratings:


 1 Reply(s)
 331  View(s)
Rate this:
Hi Everyone,
I want to use singleton design pattern in my program. Please any one can give me a appropriate example.

Thank You. 


Anupam Mishra

Total Post:135

Points:949
Posted on    January-26-2016 11:46 PM

You are building an application in C#. You need a class that has only one instance, and you need to provide a global point of access to the instance. You want to be sure that your solution is efficient and that it takes advantage of the Microsoft .NET common language run time features. You may also want to make sure that your solution is thread safe.
using System;

public class Singleton
{
   private static Singleton instance;

   private Singleton() {}

   public static Singleton Instance
   {
      get 
      {
         if (instance == null)
         {
            instance = new Singleton();
         }
         return instance;
      }
   }
}

This implementation has two main advantages:

  • Because the instance is created inside the Instance property method, the class can exercise additional functionality (for example, instantiating a subclass), even though it may introduce unwelcome dependencies.

  • The instantiation is not performed until an object asks for an instance; this approach is referred to as lazy instantiation. Lazy instantiation avoids instantiating unnecessary singletons when the application starts.

  • The main disadvantage of this implementation, however, is that it is not safe for multithreaded environments. If separate threads of execution enter the Instance property method at the same time, more that one instance of the Singleton object may be created. Each thread could execute the following statement and decide that a new instance has to be created:

    if (instance == null)
    

    Various approaches solve this problem. One approach is to use an idiom referred to as Double-Check Locking . However, C# in combination with the common language run time provides a static initialization approach, which circumvents these issues without requiring the developer to explicitly code for thread safety.


    Don't want to miss updates? Please click the below button!

    Follow MindStick