Singleton Vs Static in C#

Singleton is one the most common use design pattern, usually we use this when we have to deal with single instance creation like logger implementation. Static is keyword which ensure the special behavior in context of OOPS can have static method only.

Both singleton and static allows a single instance to be created and easily accessed.

There are several requirements associated with the singleton implementation i.e it should be ‘Thread Safe‘ means the shared data object should work well in context of multi threading execution and the ‘lazy loading‘- instance not created until it is first needed.

public sealed class with static and private constructor.

Keywords:

Sealed  class can not be inherited.

private static readonly

lock–  use to make thread safe.

Thread safety can be implemented without lock keyword. example:

public sealed class Singleton{

private static readonly Singleton instance = new Singleton();

Static Singleton(){}  //staic constructor

private Singleton(){}

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

}

For Fully Lazy initialization- Include sub class inside singleton class.

public sealed class Singleton
{
private Singleton()
{
}

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

private class Nested
{
// Explicit static constructor to tell C# compiler
// not to mark type as beforefieldinit
static Nested()
{
}

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

Reference : http://csharpindepth.com/Articles/General/Singleton.aspx

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 )

Google photo

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

Twitter picture

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

Facebook photo

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

Connecting to %s