How to implement singleton design pattern in C#?

Total Post:135

C#  .NET 
 1040  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. 
  1. Post:135

    Re: How to implement singleton design pattern in C#?

    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
             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.

      Modified On Apr-11-2018 12:55:58 AM