views:

955

answers:

2

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  A: 

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

Mehrdad Afshari
But, can the above scenario exists? That is, can there be more than one instance of a static class?
Bhaskar
Nope. It can't happen.
Mehrdad Afshari
+15  A: 

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.

Jon Skeet