Singleton Design Patten in C#


The singleton pattern is one of the most known and easiest design patterns in software engineering. In simple words, a singleton is a class which only allows a single instance of itself to be created. There are various different ways to implement this pattern in C#. In this tutorial, I will show you how you can implement the singleton design pattern with minimum amount of code.

public class LoginForm 
{ 
   private static bool instance_flag = false; 
   
   // Private Constructor to block direct object creation
   private LoginForm()
   { } 
   
   public static LoginForm instance() 
   { 
      if (instance_flag) 
      { 
         return null; 
      } 
      else 
      { 
         instance_flag = true; 
         return new LoginForm(); 
      } 
   } 

   // Class Destructor to reset instance_flag 
   ~LoginForm() 
   { 
      instance_flag = false; 
   } 
}

Following C3 Console application shows how to use a singleton LoginForm class. The first object f1 is created properly while attempt to create second instance f2 will return null.

class Program 
{ 
    static void Main(string[] args) 
    { 
       LoginForm f1 = LoginForm.instance(); 
       Console.WriteLine(f1); 
 
       LoginForm f2 = LoginForm.instance(); 
       Console.WriteLine(f2); 

       Console.Read();
    } 
}

 

 

About author


User avatar

Waqas Anwar

Founder of EzzyLearning.com, Senior Consultant, Microsoft .NET and Web Technologies

Comments