I was thinking about the classic issue of lazy singleton initialization - the whole matter of the inefficiency of:
if (instance == null)
{
instance = new
To prevent from having to copy the singleton code, you could make the type generic, as such:
public abstract class Singleton
where T: class, new()
{
public static T 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 T instance = new T();
}
}
public sealed class MyType : Singleton
{
}
class Program
{
static void Main()
{
// two usage pattterns are possible:
Console.WriteLine(
ReferenceEquals(
Singleton.Instance,
MyType.Instance
)
);
Console.ReadLine();
}
}