Serialize a Static Class?

Viewed 43845

What happens if we serialize a static class? Can more than one instance of the static class be created if we serialize it?

[Serializable]
public static class MyClass
{
    public static MyClass()
    {

    }

    public static bool IsTrue()
    {
       return true;
    }
}

Suppose I XmlSerialize the object to a XML file, and at a later time I de-serialize back to a object. Another copy exists in the memory (created when somone instintiated the static calss for the first time). Will, there be two copy of the of the object? If yes, can we stop that? Does it apply to any class which follows the singleton pattern?

7 Answers

Why not just use a temporary instance class that is a mirror of the static class?

[XmlRoot]
public class SerializeClass
{
    public int Number {
        get;
        set;
    }
}

public static class SerializedClass {

    public static int Number {
        get;
        set;
    }


    public static void Serialize(Stream stream) {

        SerializeClass obj = new SerializeClass();
        obj.Number = Number;

        XmlSerializer serializer = new XmlSerializer(typeof(SerializeClass));
        serializer.Serialize(stream, obj);
    }

    public static void Deserialize(Stream stream) {

        XmlSerializer serializer = new XmlSerializer(typeof(SerializeClass));
        SerializeClass obj = (SerializeClass)serializer.Deserialize(stream);

        Number = obj.Number;
    }
}

I know it's a bit of a hack, but it acheives the same purpose, while still allowing Refactor before runtime, and value validation during runtime.

I found an interesting hack to keep a static class and enable it to make it readable by the xml serializer.

Keep your class non-static but put it in another class which is static

namespace Example
{
    static public class C
    {
        public static MyClass myClass = new MyClass();
    }
}

Then you can use the xml serializer to serialize/deserialize like this

Method :

public void WriteMyClass (string savepath, MyClass myClass)
    {
        XmlSerializer xmlSerializer = new XmlSerializer(typeof(MyClass));
        XmlWriter xml_Writer;
        XmlWriterSettings xml_Settings = new XmlWriterSettings();

        xml_Settings.NewLineOnAttributes = true;
        xml_Settings.Indent = true;

        xml_Writer = XmlWriter.Create(savepath, xml_Settings);
        xmlSerializer.Serialize(xml_Writer, myClass);
        xml_Writer.Close();
    }

Use :

WriteMyClass(savepath, C.myClass);

I know it may not be the cleaner way, but this may combine XML Serializer and static class, but MyClass can be instantiated in other parts of your code, so be carefull about that.

Hope this may help.

Related