Here in this post i am depicting the most common pattern in our software life, the singleton pattern. But there is another catch on how .Net is designed to handle this pattern. Below is the code for a typical single ton pattern.
// Static members are lazily initialized.
// .NET guarantees thread safety for static initialization
private static readonly Singleton instance;
// Note: Constructor is 'protected' but of course child objects can access
public static Singleton Instance()
when we say singleton it should not create more than one instance at any point of time at any cost and thereby it should ensure a class has only one instance and provide a global point of access to it.
From the above code it is obvious that no one can create an instance of this class because it is having a private/Protected constructor
But any idea what will happen if you try to de-serialise an instance of this anywhere outside the class?
Yes. In this scenario a new instance of the class would be created and the values from the incoming stream will be assigned to it.
Seems disgusting? Confused? You think that the whole pattern and .Net has broken its rules. These are some of the scenarios which .Net considers as special situations. So .Net CLR is designed in such a way that it allows only the serialising engine to create an instance of this class. And you should take care of this condition separately. Say, the serialised singleton object should always get saved to the same particular location. Or you’ll end up in n number of instance for a singleton object. J.