C# Singleton Pattern

The Singleton Design Pattern is the standard way programmers create classes which are designed to have one and only one instantiation at any point in time. These classes can be used for configurations or settings objects which are globally available and which need to maintain state when being read or updated by various portions of the application.

This is accomplished by making the class Constructor private so that it cannot be accessed. This stops the class from being instantiated by code external to the class itself. Then a public property is exposed which retrieves a reference to an existing instance of the class stored in a local variable or if an instance does not yet exist the class creates a new instance and saves the reference for later calls.

Example Code:

1 public sealed class MySingleton

2 {

3 private static volatile MySingleton instance;

4 private static object syncer = new Object();


6 private MySingleton() { }


8 public static MySingleton Instance

9 {

10 get

11 {

12 if (instance == null)

13 {

14 lock (syncer)

15 {

16 instance = new MySingleton();

17 }

18 }

19 return instance;

20 }

21 }

22 }

Published by

Tim Clark

Experienced Business Owner, Chief Information Officer, Vice President, Chief Software Architect, Application Architect, Project Manager, Software Developer, Senior Web Developer, Graphic Designer & 3D Modeler, University Instructor, University Program Chair, Academic Director. Specialties: Ruby, Ruby on Rails, JavaScript, JQuery, AJAX, Node.js, React.js, Angular.js, MySQL, PostgreSQL, MongoDB, SQL Server, Responsive Design, HTML5, XHTML, CSS3, C#, ASP.net, Project Management, System Design/Architecture, Web Design, Web Development, Adobe CS6 (Photoshop, Illustrator)

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s