Singleton Pattern in c#

Singleton :-

1> Allows only one time object creatation.

lets move to the code.


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

namespace ConsoleApp1
{

    class Singleton
    {
        private Singleton() { }// constructor must be private or protected to avoid calls from  new                                                         //operator
        private static Singleton _initation =null; //To store singleton instance in static field.

        public static Singleton GetInitation()//  static method. to instantiate singleton object.
        {
            if (_initation == null)
            {
                _initation = new Singleton();
            }
            return _initation;

        }
       
    }
    class Program
    {
        static void Main(string[] args)
        {
            Singleton s = Singleton.GetInitation();
            Singleton s1 = Singleton.GetInitation();

            if (s == s1)
            {
                Console.WriteLine("Singleton");
            }

            Console.ReadLine();
        }
    }
}

output:- Singleton

Share this

Previous
Next Post »