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:
Hello,

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);
try
{
    // 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);
    throw;
}
finally
{
    fs.Close();
}


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

[EDIT]
below is the code of how singleton class is created
C#
using System.Runtime.Serialization;
using System.Runtime.Serialization.Formatters.Binary;


namespace Namespace
{
    [Serializable]

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

        private Singleton() { }

        public static Singleton GetInstance
        {
            get
            {                
                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)
        {

            info.SetType(typeof(SingletonSerializationHelper));
        }




Thanks in Advanced.
Posted
Updated 20-Mar-12 22:30pm
v4
Comments
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.
--SA

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:
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
 
Share this answer
 
v2
Comments
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=1.0.0.0, 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].
--SA
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?
--SA
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