Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Serialize a Static Class?

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?

like image 282
Bhaskar Avatar asked Aug 18 '09 12:08

Bhaskar


People also ask

Can you serialize a static class C#?

You can't serialize static classes (or any class whatsoever) using built-in . NET serialization features. You can only serialize instances of classes.

Do static fields get serialized?

static fields aren't serialized.

Can we save static data member using serialization?

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.


1 Answers

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.

like image 186
Jon Skeet Avatar answered Sep 19 '22 09:09

Jon Skeet