Jerry Nixon @Work: Implementing the WinForm Singleton Pattern

Jerry Nixon on Windows

Thursday, December 15, 2005

Implementing the WinForm Singleton Pattern

In a recent project I had to implement the Singleton WinForm Pattern. This Pattern is essential for performance and pretty darn easy to use.

The idea is that each form in the WinForm application has only one unique instance in an individual AppDomain. So, here's what you don't do:

Application.MyForm _MyForm;
_MyForm = new Application.MyForm();


Why? Because calling New results in a brand new instantiation of the form. Instead, with Singleton we ask for the instance of the form like this:

Application.MyForm _MyForm;
_MyForm.GetInstance();


How does it work? Well, the only form that exists is a private static variable that instantiates when the static constructor fires. Here's what it looks like:

public sealed class MyForm
{
private static MyForm m_instance = new MyForm();
public static MyForm GetInstance()
{
return m_instance;
}
}


Is it thread safe? Yes.

It's good practice to make the class sealed.


Hey! This isn't limited to WinForms - any class can use it.


I hope this helps.


Easy huh?