Mmm, I disagree -
1. The static ctor is only lazy in the sense the singleton only exists when you access its type, but the lazy initialization that was suggested, initializes the singleton when the instance is first called.. the difference in this is that you may have shared
methods on the type that don't nec need the singleton instance.
2. I thought double check locking was the only way to safely access objects that may be used by multiple threads.. is it really true that you can't say for sure they work? why do we even bother then?
And I don't really agree with your argument against the singleton, using names like 'global variable' to describe it, makes it sound very ugly, when it isn't like that at all...
1. You can achieve this easy enough, _IF REQUIRED_, by using an internal static class to handle the instantiation of the specific object.
2. The only way to safely access objects that may be used by multiple threads is by using a synchronization primitive. DCL isn't a primitive. It's a poorly designed pattern meant to optimize the synchronization when an object will be read many times but
written to only once. The problem is, this pattern only works on architectures with a specific memory visibility model. There are architectures that do not have this visibility model, and the DCL pattern leads to a race condition that can cause multiple
threads to "initialize" the data, possibly leading to memory corruption or other errors. If you're writing portable code, or don't have a guarantee about the memory model for your target architecture, you should never use the DCL. I do not believe the CLR
makes any gaurantees here, so you shouldn't use the DCL. The reality is that, today, on x86 architectures using the Microsoft supplied CLR, the DCL is "safe." But for all of the reasons I just gave, including the fact that future x86 architectures could
well change the memory model, I simply can not recommend anyone use this pattern. Trust me, you're better off forgetting this pattern exists. Even the originator of this pattern acknowledges the problems and short comings of it now.
Oh, and I'm sorry, but a Singleton IS a variant on a "global variable". I'm not saying there's not a place for a Singleton, or any form of "global variable" for that matter. I'm saying there are real issues that must be considered when you choose to use one,
and in general they are used far more often than they need to be, or should be. Consider alternate designs first. If the singleton is still your best option, fine. But that really isn't the case very often.