Web
Analytics
singleton design pattern asp.net C# | Angular | ASP.NET Tutorials

For Consultation : +91 9887575540

Stay Connected :

What is singleton pattern

1.A class Object having only one instance and able to perform all task.

2.This design pattern is considered as creational(object creation) design pattern.

3.No constructor parameters are allowed while creating an instance.

How to implement singleton design pattern in C#

▸A single constructor, that is private and parameterless.

▸The class is sealed.

▸A static variable that holds a reference to the single created instance, if any.

▸A public static means of getting the reference to the single created instance, creating one if necessary.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace SingltonDesignPattern
{
    class Program
    {
        static void Main(string[] args)
        {
            Singlton obj1 = Singlton.MyObject();
            obj1.mymethod();
            Singlton obj2 = Singlton.MyObject();
            obj2.mymethod();
            Console.ReadLine();
        }
    }
    sealed class  Singlton
    {
        private Singlton()
        {

        }
        public static Singlton getinstnace = null;
        public static Singlton MyObject()
        {
            if(getinstnace==null)
            {
                return new Singlton();
            }
            return getinstnace;
        }
        public void mymethod()
        {
            Console.WriteLine("This is my Method");
        }
    }
}