If your singleton is a static class, the whole idea of serialization in this way makes no sense in principle.
To explain it, let's assume for a minute you managed to serialize it somehow. Now, look at the binary formatter class you use:
http://msdn.microsoft.com/en-us/library/system.runtime.serialization.formatters.binary.binaryformatter%28v=vs.100%29.aspx[
^].
To deserialize, you would need to use the method
public Object Deserialize(Stream serializationStream)
. It returns the object of the type (compile type)
System.Object
. What would be the runtime type if this object? It supposed to represent the object of the type you have serialized before. But such object cannot exist, because static classes cannot have instances!
You are done, case closed.
Now, what do you want to do? First of all, the singleton implemented as a static class is a bad implementation. Please take a look at something better:
http://csharpindepth.com/Articles/General/Singleton.aspx[
^].
Look at this implementation. The class itself is never a static one. If has instance, but the instance is static. It is important that it is private, for proper encapsulation. And the instance can be serialized.
[EDIT]
In response to the follow-up question:
The missing thing is the attribute
[System.Serializable]
. Please see
System.SerializableAttribute
:
http://msdn.microsoft.com/en-us/library/system.serializableattribute%28v=vs.100%29.aspx[
^].
All the types in you object graph should be marked serializable, of course.
—SA