Objects in this mirror are closer to Microsoft Technologies. DNM objective is to help users on Microsoft technologies by providing Articles, snippets, Interview Questions.

04 June 2012

Singleton class in C#.NET

In the article we will discuss about singleton class in C#.NET.

Definition:
“A class which can be instantiated only once is called singleton class”.
The term singleton is derived from the mathematics concept of a singleton. Singleton is set with only one element. E.g.: Set {0} is a singleton.

How to achieve singleton class?
  • Mark the constructor as private so that outside the class it’s not possible to create instance of the class.
  • Create static/Shared method can be added to the class to create instance of the class and return the reference of the object.
Example:
class SingletonClass
    {
        private static Singlet
onClass obj;
        public int tempVal
        {
            getset;
        }
        //private constuctor
        private 
SingletonClass()
        {
        }
        public static Singleto
nClass GetInstance()
        {
            if (obj == null)
            {
                obj = new Sing
letonClass();                
            }
            return obj;
        }
    }
    class SingletonClassProgra
m
    {
        public static void 
Main(string[] args)
        {
            SingletonClass 
obj1,obj2;
            //obj1=new 
SingletonClass(); //invlid 
due to constructore is private. Error as inaccissible due to protection level
             obj1=SingletonCla
ss.GetInstance();
            obj1.tempVal =20;
            obj2=SingletonClas
s.GetInstance();
            Console.WriteLine(
" /********* singleton class 
Example **********/");
            Console.WriteLine(
"variable value is {0}",obj2.
tempVal); //value is 20 because both obj1,obj2 are referring to same object
            Console.Read();
        }
    }
Output:



Data points:
  • Singleton is a design pattern in software development.
  • Singleton class is like a sealed class

0 Comments:

Post a Comment