An obvious singleton implementation for .NET?
.net, c#, singleton
Solution
This is the canonical, thread safe, lazy Singleton pattern in C#:
public sealed class Singleton
{
Singleton(){}
public static Singleton Instance
{
get
{
return Nested.instance;
}
}
class Nested
{
// Explicit static constructor to tell C# compiler
// not to mark type as beforefieldinit
static Nested() {}
internal static readonly Singleton instance = new Singleton();
}
}
Problem
I was thinking about the classic issue of lazy singleton initialization - the whole matter of the inefficiency of: ``` if (instance == null) { instance = new Foo(); } return instance; ``` Anyone who knows what a Singleton is is familiar with the issue(you only need the if once). It's trivial but irritating. So, I thought of an alternate solution, at least for .NET(although it should work anywhere that has some equivalent to function pointers: ``` public class Foo { private delegate Foo FooReturner(); private static Foo innerFoo; private static FooReturner fooReturnHandler = new FooReturner(InitialFooReturner); public static Foo Instance { get { return fooReturnHandler(); } } private static Foo InitialFooReturner() { innerFoo = new Foo(); fooReturnHandler = new FooReturner(NewFooReturner); return innerFoo; } private static Foo NewFooReturner() { return innerFoo; } } ``` In short - the Instance returns a delegate method. The delegate is initially set to a method that initializes your instance, then changes the delegate to point at a simple Return method. Now, I like to think I'm not terrible at my job, but I have no pretensions about being awesome. I have not seen an example of this code anywhere. Ergo, I come to the conclusion that I am missing something. Something major. Either that the whole problem is too trivial to bother thinking that much about or this does something horrible that will destroy the universe. Or I fail at searching and therefore haven't seen the hundreds of developers using this method. Something, anyway. I was hoping the good folks here at Stack Overflow could clue me in as to what(leaving aside the controversy on whether one should use a Singleton at all). EDIT for clarification: This is not performance code(although if the design actively degrades performance beyond the traditional model, that would be interesting to know). It was written purely as proof-of-concept, and I am further aware that it is not thread-safe as it properly should be. Is there any reason why it could NOT be made thread-safe by it's very nature?