Coding Schools


 
Python | C Sharp | Azure AI | HTML | JavaScript | CSS | SQL Server
OOPS in C#
C# Data Types
Boxing and Unboxing in C#
Garbage Collection in C#
C# - Conditional Statements
C# - Loops
Interfaces in C#
Generics in C#
Collections in C#
C# 8.0 new features
C# Singleton Design Pattern
C# Factory Design Pattern
LINQ in C#
C# - Program to Find Prime Numbers
C# - Fibonacci Sequence
C# - Factorial of a number
C# - Recursive methods
C# - Anonymous Methods
C# - String Methods
C# TDD - XUnit
C# TDD - NUnit
C# Multiton Design Pattern
C# Facade Design Pattern
C# Abstract Factory Design Pattern
C# Decorator Design Pattern
C# Composite Design Pattern

C# Singleton Design Pattern



The Singleton Design Pattern in C# ensures that a class has only one instance and provides a global point of access to that instance. Singleton is useful for situations where you need to control access to a shared resource such as configurations, a shared logger, or a connection pool.

Characteristics of Singleton

  1. Single Instance: Only one instance of the class exists.

  2. Global Access: Provides a global point of access to the instance.

  3. Controlled Instantiation: Direct instantiation is prevented.

Implementing Singleton in C#

Here are some common ways to implement the Singleton pattern in C#:

1. Basic Singleton Implementation

This is the simplest form of Singleton using lazy instantiation to ensure the instance is created when it is needed.

csharp
public class Singleton
{
    // Private static variable to hold the single instance
    private static Singleton _instance;

    // Private constructor to prevent direct instantiation
    private Singleton() { }

    // Public static method to provide global access to the instance
    public static Singleton Instance
    {
        get
        {
            if (_instance == null)
            {
                _instance = new Singleton();
            }
            return _instance;
        }
    }
}

2. Thread-Safe Singleton

This ensures that multiple threads do not create multiple instances of the Singleton.

csharp
public class Singleton
{
    // Private static variable to hold the single instance
    private static Singleton _instance;
    private static readonly object _lock = new object();

    // Private constructor to prevent direct instantiation
    private Singleton() { }

    // Public static method with double-check locking for thread safety
    public static Singleton Instance
    {
        get
        {
            if (_instance == null)
            {
                lock (_lock)
                {
                    if (_instance == null)
                    {
                        _instance = new Singleton();
                    }
                }
            }
            return _instance;
        }
    }
}

3. Lazy<T> Singleton

Using Lazy<T> ensures thread-safe lazy initialization without the need for double-check locking.

csharp
public class Singleton
{
    private static readonly Lazy<Singleton> _lazyInstance = new Lazy<Singleton>(() => new Singleton());

    private Singleton() { }

    public static Singleton Instance => _lazyInstance.Value;
}

Usage Example

Here's how you can use the Singleton class:

csharp
class Program
{
    static void Main()
    {
        Singleton instance1 = Singleton.Instance;
        Singleton instance2 = Singleton.Instance;

        if (instance1 == instance2)
        {
            Console.WriteLine("Both instances are the same.");
        }
    }
}

Benefits of Singleton Pattern

  • Controlled Access: Only one instance means controlled access to resources.

  • Reduced Overhead: Minimizes the overhead associated with creating and managing multiple instances.

  • Global State: Provides a global point of access to the instance, ensuring consistency.

Considerations

  • Testing: Singletons can make unit testing challenging, as they maintain global state.

  • Lifetime: Ensure that the Singleton's lifetime aligns with the application's requirements.

  • Concurrency: Be mindful of thread safety when implementing Singletons in multi-threaded environments.

By following these approaches, you ensure that your Singleton implementation is both efficient and robust. If you have more specific use cases or scenarios in mind, feel free to share!




All rights reserved | Privacy Policy | Sitemap