Tuesday, March 24, 2009

Generic Singleton Pattern - C#

I was trying to reinvent the wheel, trying to create a generic version of the Singleton Pattern for our .net Objects.

The code itself its self-explanatory.

However I found it here:

Pasted code below:

public static class Singleton where T : class, new()

{

private static readonly object syncRoot = new object();

private static T instance;

public static T Instance

{

get

{

if (instance == null)

{

lock (syncRoot)

{

if (instance == null)

{

var tempInstance = new T();

Thread.MemoryBarrier();

instance = tempInstance;

}

}

}

return instance;

}

}

}

No comments: