Post Details

What is the Singleton Design Pattern in C Sharp .Net ?

np

Fri , Aug 04 2023

np

Article 1 on design pattern-

What is the Singleton Design Pattern in C#? 

The Singleton Design Pattern is a creational design pattern that ensures that a class has only one instance and provides a global point of access to it. It is used when only one instance of a class is required to control the action throughout the execution. Here is an example of the Singleton Design Pattern in C#

using System;

public sealed class Singleton

{

    private static Singleton instance = null;

    private static readonly object padlock = new object();


    Singleton()

    {

    }


    public static Singleton Instance

    {

        get

        {

            lock (padlock)

            {

                if (instance == null)

                {

                    instance = new Singleton();

                }

                return instance;

            }

        }

    }

}


class Program

{

    static void Main()

    {

        Singleton s1 = Singleton.Instance;

        Singleton s2 = Singleton.Instance;


        if (s1 == s2)

        {

            Console.WriteLine("Only one instance exists.");

        }


        Console.ReadKey();

    }

}


1 Comments

np
np

02 Feb 24

another simple example of singleton design pattern is mentioned below-using System;public class Hell...

Leave a Reply

Please log in to Comment On this post.