An exception thrown inside Singletin's .ctor will be thrown on type initialization (instead of first access to Instance property and even if you will never use it) and wrapped into TypeInitializationException. Alternative 6 solves that without any performance loss.
It is wrong that an exception might be thrown "even if never used". Because the field is static, it will be created when the class is first accessed. So an exception thrown by the constructor would still only occur at the first call to "instance" (assuming it is the only publicly accessible member of the class). See my reply to Kabwla.Phone, above.
An exception thrown inside Singletin's .ctor will be thrown on type initialization (instead of first access to Instance property and even if you will never use it)
This is not quite correct! If you never call "Instance", the exception will never be thrown, even if you explicitly create one like this (because the type will not ever get initialised). In other words, the exception would still get thrown the first time the class is required, i.e. in the former case, "just before" the call to Instance is made.
You are correct that if there should be an error in the constructor then the former pattern can be harder to debug. However, I wonder if you've forgotten that an exception should be just that - exceptional! It may well be that if the instance class fails to be instantiated that the application could not continue anyway, so allowing the application to terminate can be the best option. And if you have a very simple class that should not throw an exception, then the former pattern may be better (e.g. it gets around the need for your own locking mechanism in the Instance method, and the overhead involved in that. Although of course, you mustn't forget that you may need to allow for locking mechanisms in the class's members!)
This is why I will not say that one pattern is better than the other. It's all about design.
As I said in my reply to Kabwla.Phone[^], there are pros and cons to each pattern. I nearly mentioned the problem of the difficulty to debug, but must have decided not to do so as my responses were all getting rather long.
Last Visit: 31-Dec-99 18:00 Last Update: 21-Oct-14 13:29