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?
You can't serialize static classes (or any class whatsoever) using built-in . NET serialization features. You can only serialize instances of classes.
static fields aren't serialized.
Static data members and transient data members are not saved via Serialization process.So, if you don't want to save value of a non-static data member then make it transient.
There are never any instances of static classes: they are both abstract and sealed in the IL, so the CLR will prevent any instances being created. Therefore there is nothing to serialize. Static fields are never serialized, and that's the only sort of state that a static class can have.
Your question about XML serialization makes no sense, as no-one can ever have created an instance of the static class to start with.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With