---
title: "Winform Singleton pattern example"
url: "https://osherove.com/blog/2004/1/23/winform-singleton-pattern-example.md"
canonical: "https://osherove.com/blog/2004/1/23/winform-singleton-pattern-example.html"
published: "2004-01-23T09:33:00"
updated: "2004-01-23T09:33:00"
tags: [".Net Original"]
author: "Roy Osherove"
description: "Stefano describes how he implements the Singleton design pattern for a form object in a winform application. I disagree. The main points of a Singleton: No new instances of the Singleton class can be created There…"
usage: "Licensed under CC BY 4.0 — reuse, quote and adapt with attribution (Roy Osherove, link to the original page)."
license: "https://creativecommons.org/licenses/by/4.0/"
---

# Winform Singleton pattern example

By Roy Osherove January 23, 2004 In [.Net Original](https://osherove.com/blog/category/net-original)

**Historical article** · Originally published January 23, 2004; technical details may be outdated.

[Stefano describes](http://dotnetjunkies.com/WebLog/demiliani/posts/5961.aspx) how he implements the [Singleton](http://www.c-sharpcorner.com/Code/2003/Jan/SingletonPattern.asp) design pattern for a form object in a winform application.

I disagree. The main points of a Singleton:

- No new instances of the Singleton class can be created
- There should be one existing instance for use which cannot be destroyed

To do this in a winform the steps should be:

- Make the constructor private (so that no one create a new instance)
- Add a private shared \_instance variable of type Form1
- Add a public shared and **readonly** property that exposes the variable, called "Instance"
- Use this property to run the application

Here's an example(VB.NET):

Public Class Form1

    Inherits System.Windows.Forms.Form

    Private Shared \_instance As New Form1

    Public Shared ReadOnly Property Instance() As Form1

        Get

            Return \_instance

        End Get

    End Property

    Private Sub New()

        MyBase.New()

        'This call is required by the Windows Form Designer.

        InitializeComponent()

        'Add any initialization after the InitializeComponent() call

    End Sub

End Class

 

 Module Module1

    Public Sub Main()

        Application.Run(Form1.Instance)

    End Sub

End Module

**Update**

[Stuart adds a very important comment](http://www.bistrotech.net/weblog/PermaLink.aspx?guid=db05f620-6dd4-4302-8e48-3fc70aafb0c7) which I did not think of (That's what happens when you talk about stuff you never actually had to implement before I guess):

_Forms are a slightly more complex animal than other classes in that a form instance can be destroyed at will by the end user.  When a form is closed, its controls and its base class are disposed.  This is not desired behavior in a singleton class because once an object has been disposed, it can no longer be accessed (or, in the case of a form, displayed).  To see this undesired behavior in action, simply attempt to launch Roy's singleton form twice in succession and observe the System.ObjectDisposedException that gets thrown._

_Solving this problem is easy, though.  Simply override OnClosing(), cancel the close, and hide the form instead._

   Protected Overrides Sub OnClosing(ByVal e As System.ComponentModel.CancelEventArgs)
      e.Cancel = True
      Me.Hide()
   End Sub

_Now when the user closes the form, the form merely hides instead of disposing and everything works as expected (until you start trying to use singleton forms as MDI children, but that's the subject of a_ [**_different post_**](http://www.bistrotech.net/weblog/PermaLink.aspx?guid=42b9962a-9016-4e8c-8ff4-5cca9eb5b2c7)_)._ 

## More in .Net Original

[All posts in .Net Original](https://osherove.com/blog/category/net-original)

- Feb 17, 2004

    ### [\[Article\] Make your .Net application support scripting - the practical way](https://osherove.com/blog/2004/2/17/article-make-your-net-application-support-scripting-the-prac.html)

- Feb 11, 2004

    ### [Watch me speak at IVCUG: Regex and Plugins](https://osherove.com/blog/2004/2/11/watch-me-speak-at-ivcug-regex-and-plugins.html)

- Jan 22, 2004

    ### [Israel DevDays](https://osherove.com/blog/2004/1/22/israel-devdays.html)

- Jan 22, 2004

    ### [Convert a DataReader into a DataSet](https://osherove.com/blog/2004/1/22/convert-a-datareader-into-a-dataset.html)


---

## About the author

**Roy Osherove**: Senior Solutions Architect at AWS working on AI for production and AI-driven development; author of The Art of Unit Testing and Elastic Leadership, with about 20 years of consulting and training on unit testing, TDD, team leadership and continuous delivery.

### Sites

- [RobotPaper](https://robotpaper.ai/): This blog: AI patterns and anti-patterns, AI and coding agents, and engineering leadership.
- [osherove.com](https://osherove.com): Roy's personal site. Author of The Art of Unit Testing and Elastic Leadership; consulting and training on unit testing, TDD, team leadership and continuous delivery, plus about 20 years of blog posts.
- [The Art of Unit Testing](https://www.artofunittesting.com): The Art of Unit Testing, 3rd Edition (Manning): readable, maintainable, trustworthy unit tests, plus TDD workshops in C#, JavaScript, Java and Kotlin.
- [5whys.com](https://www.5whys.com): Roy's writing on software team leadership: self-organizing teams, surviving chaos, learning mode and the Elastic Leadership model.
- [Pipeline Driven](https://pipelinedriven.org): Continuous delivery and DevOps practices: build patterns, pipeline-friendly testing, DevOps metrics and enterprise DevOps.
- [Elastic Leadership](https://www.elasticleadership.com): Elastic Leadership, Roy's framework for software team leaders (survival, learning and self-organizing modes).

### Social

- X: https://x.com/royosherove
- LinkedIn: https://www.linkedin.com/in/osherove/

### Contact

- Contact form: https://forms.gle/jQSx5KoXvrVA1JCK7

### License

Licensed under CC BY 4.0 — reuse, quote and adapt with attribution (Roy Osherove, link to the original page). License: https://creativecommons.org/licenses/by/4.0/
