I'll be posting a series of Live Templates I've created, as JetBrains has not yet created a community site where we can share and import directly from Visual Studio yet. (hint, hint).
Singleton
First a quick note. The obvious way to implement singletons in c# is not thread safe:
public sealed class Singleton
{
static Singleton instance=null;
Singleton()
{
}
public static Singleton Instance
{
get
{
if (instance==null)
{
instance = new Singleton();
}
return instance;
}
}
}
For an excellent discussion on the topic, read Jon Skeet
I based my template on his solution 4:
public sealed class Singleton
{
static readonly Singleton instance=new Singleton();
// Explicit static constructor to tell C# compiler
// not to mark type as beforefieldinit
static Singleton()
{
}
Singleton()
{
}
public static Singleton Instance
{
get
{
return instance;
}
}
}
This, and my other currently used Live Templates can be had here (right click, Save): Live Templates Download
#region Singleton
private static readonly $ClassName$ _instance = new $ClassName$();
static $ClassName$(){}
private $ClassName$(){}
public static $ClassName$ Instance
{
get { return _instance; }
}
#endregion