C# Creating a Singleton

A lot of people talk trash about the Singleton and how it should be avoided like the plague. I think like a lot of things it has its place and can be used effectively in certain situations. I'm going to leave what those situations are alone for the time being and just focus on creating a nice thread safe lazy init singleton class.

public sealed class Singleton
{
Singleton()
{
}

public static Singleton Instance
{
get
{
return Nested.instance;
}
}

class Nested
{
// Use an explicit static constructor to tell the C# compiler
// not to mark type as beforefieldinit
static Nested()
{
}

internal static readonly Singleton instance = new Singleton();
}
}

Comments

Popular posts from this blog

String.Replace vs Regex.Replace

C# Form Application in Kiosk Mode/Fullscreen

C# using a transaction with ODBC