I came across this answer by Marc Gravell on how to create an object without calling its constructor. Can someone confirm this will not circumvent even the complete and best implementation of singleton pattern(Reference implementations here. And why? I guess more specifically I am not clear on the inner workings of GetSafeUninitializedObject() in the context of a Class’s constructors (static, private etc)
Share
Within the singleton pattern you have a static variable on your type that will be initialized by the type constructor.
By calling
GetSafeUninitializedObjectyou only avoid the instance constructor which will be called after the type constructor.Example:
Update to clarify difference between type initializer and static ctor asked from IllidanS4
This doesn’t really belong to the answer above, but to the question within the comments: And a answer simply doesn’t fit into a simple comment.
@IllidanS4: The type initializer is just a shortcut for writing an implicit static constructor. If you create a class that contains both initialization methods and decompile the resulting assembly you can see only one static constructor (.cctor) that will initialize all the variables. The both assignments will be merged where the type initializer will be called first and the statements within the static constructor last.
Take this sample class:
If you compile it and afterwards decompile it (e.g. by using ILSpy) you’ll get the following code back:
Due to this fact i normally never use to initialize a variable directly when it will be declared. Instead i always leave them uninitialized (like the
ByTypeCtorvariable) and make all initializations within the constructor. This simply avoids cluttering variable initialization to different positions within the class which improves maintainability.