﻿# Best article I've found on the Singleton Pattern in C#

<datetime class="hidden">2004-01-31T00:00</datetime>
<!-- category -- mostlylucidcouk, Imported, C#, Architecture, Software Development -->

Have a read at this article on implementing the [SIngleton pattern](http://www.yoda.arachsys.com/csharp/singleton.html) in C#. No idea what I'm on about? Well, the Singleton Pattern isn't a knitting method for the lonely, it's one of the most important techniques for ensuring that two people - on the web its' mostly separate people - for instamce, don't try to read and write a resource at the same time. A Singleton is defined as an object which is allowed only a single instance within an application context - so all uses of the functionality provided by that object are handled by this single instance.

As an example, say you have a text file which contains some XML data and is used as a database of sorts...well, you obviously want to avoid someone writing to the file at the same time as you're trying to read it - at best you'll get locking problems. at worst you could corrupt the data entirely. The Singleton pattern would help in this situation by providing a single gateway to access that file - so all operations on that file would become concurrent rather than simultaneous, avoiding the read / write scenario described previously.

Another classic ASP.NET example is in the management of cached items - where you can be unfortunate enough to have 2 threads trying to update a cache at the same time; there is a solution to this using [thread locking](http://www.asptoday.com/content.asp?id=2239)but a Singleton is much purer architecturally and easier to scale at a later date should you need to provide this interface to more items. Anyway, if you're just starting out with patterns, have a look at the article above or, one of the best books on patterns in .NET applications (thus far, theres lots more just released), have a look at [Patterns Of Enterprise Architecture](http://www.amazon.co.uk/exec/obidos/ASIN/0321127420/mostlylucid-21) - I'm still waiting for Design Patterns for Web Applications using ASP.NET - who wants to write this?
But be warned, be careful where you choose to use a Singleton - it can affect performance and bottlenecks if not used carefully. With much power comes much responsibility!