D
David Veeneman
Why do these questions always come up on Friday afternoon?
I'm starting to use GoF singleton classes in my projects. Right off the bat,
I've run into a surprise. I thought that a Singleton could be implemented
using a static constructor, using code like this, based on version #4 at
http://www.yoda.arachsys.com/csharp/singleton.html:
public sealed class MyClass
{
private static MyClass m_MyClass = new MyClass();
static MyClass()
{
}
public static MyClass GetSingleton()
{
return m_MyClass;
}
}
According to the C# Language Specification (10.11 Static constructors), a
static constructor can't be called directly, so I'd use a call like this to
get the single instance of the class:
MyClass myObject = MyClass.GetSingleton();
However, .NET allows me to call the constructor directly:
MyClass myObject = new MyClass();
What's more, its allowing me to create multiple objects from the class. So
the Singleton approach is clearly failing.
What am I missing? Better yet, what's the simplest thread-safe approach to
implementing a Singleton in .NET 2.0? Thanks.
I'm starting to use GoF singleton classes in my projects. Right off the bat,
I've run into a surprise. I thought that a Singleton could be implemented
using a static constructor, using code like this, based on version #4 at
http://www.yoda.arachsys.com/csharp/singleton.html:
public sealed class MyClass
{
private static MyClass m_MyClass = new MyClass();
static MyClass()
{
}
public static MyClass GetSingleton()
{
return m_MyClass;
}
}
According to the C# Language Specification (10.11 Static constructors), a
static constructor can't be called directly, so I'd use a call like this to
get the single instance of the class:
MyClass myObject = MyClass.GetSingleton();
However, .NET allows me to call the constructor directly:
MyClass myObject = new MyClass();
What's more, its allowing me to create multiple objects from the class. So
the Singleton approach is clearly failing.
What am I missing? Better yet, what's the simplest thread-safe approach to
implementing a Singleton in .NET 2.0? Thanks.