Click here to Skip to main content
15,882,552 members
Please Sign up or sign in to vote.
1.67/5 (3 votes)
See more:

I am creating an application in C# which is having a singleton class.
When i am trying to serialize that class using binary serialization.
It create the file of 1KB size.

Below is my code
FileStream fs = new FileStream("DataFile.dat", FileMode.Create);
    // Construct a BinaryFormatter and use it  //to serialize the data to the stream.
     BinaryFormatter formatter = new BinaryFormatter();                
     formatter.Serialize(fs, Obj);
catch (SerializationException e)
    Console.WriteLine("Failed to serialize. Reason: " + e.Message);

Kindly let me know is the any problem in above code or tell me how to serialize Singleton class

below is the code of how singleton class is created
using System.Runtime.Serialization;
using System.Runtime.Serialization.Formatters.Binary;

namespace Namespace

public sealed class Singleton: ISerializable
        private static readonly Singleton Obj = new Singleton ();

        private Singleton() { }

        public static Singleton GetInstance
                return Obj;

        internal sealed class SingletonSerializationHelper : IObjectReference
            // This object has no fields (although it could).

            // GetRealObject is called after this object is deserialized.
            public Object GetRealObject(StreamingContext context)
                // When deserialiing this object, return a reference to
                // the Singleton object instead.
                return Singleton.Obj;
        public void GetObjectData(SerializationInfo info, StreamingContext context)


Thanks in Advanced.
Updated 20-Mar-12 22:30pm
Dean Oliver 20-Mar-12 6:55am    
whats the exception?
Sergey Alexandrovich Kryukov 20-Mar-12 22:06pm    
Dean, it does not really matter, because the whole idea of serialization such "singleton" is wrong. It cannot be done in principle. I prove it in my answer, please see.

One of the possible solutions is implementing singleton pattern correctly. Again, please see the same answer.

1 solution

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:[^].

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:[^].

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.


In response to the follow-up question:

The missing thing is the attribute [System.Serializable]. Please see System.SerializableAttribute:[^].

All the types in you object graph should be marked serializable, of course.

Share this answer
sheetal.gawde 21-Mar-12 0:42am    
In my application i want only one instance of the class. so i have 2 options, to create it as a static class or to use singleton class. I used Singleton Class, but failed to serialize that class. While serialization it create that file with size 1KB and while deserialization it gives exaption as
"Type 'classname+SingletonSerializationHelper' in Assembly 'namespace, Version=, Culture=neutral, PublicKeyToken=null' is not marked as serializable."
Sergey Alexandrovich Kryukov 21-Mar-12 2:44am    
I explained clearly why did you fail it. When and if you get the fundamentals, you need to make the class serializable. I don't know your data structure, but you should use the attribute.

Please also see my updated answer, after [EDIT].
sheetal.gawde 21-Mar-12 4:26am    
I have already added [serializable] in my class. please see my updated question[EDIT] with class definition.
Sergey Alexandrovich Kryukov 21-Mar-12 21:12pm    
OK. Any remaining problem?
sheetal.gawde 21-Mar-12 23:58pm    
I have added [serializable] in my class still its giving the same problem as written above.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900