29

By "default" I mean just using the [Serializable] attribute on the class. I want to say that no, static fields would not be serialized, but I'm not exactly sure.

Mark LeMoine
  • 4,478
  • 3
  • 31
  • 52
  • I appreciate this question b/c you can easily argue (as the answerer does) that static fields do not belong to any instance. However, once can also conversely argue that static fields belong to every instance if the Type and instances of a Type philosophy in .NET is not properly understood. Mainly b/c it is precisely that - a philosophy. The .NET documentation does not explicitly clarify this point concerning serialization, which it should. – outbred Dec 03 '14 at 23:03

1 Answers1

32

No; static fields are not serialized.

.Net serialization serializes instances; static fields do not belong to an instance.

SLaks
  • 868,454
  • 176
  • 1,908
  • 1,964
  • Thanks, that's pretty much what I wanted to clarify! – Mark LeMoine Oct 11 '10 at 03:29
  • 3
    Unhappily, the [SerializableAttribute documentation](http://msdn.microsoft.com/en-us/library/system.serializableattribute%28v=vs.100%29.aspx) says "All the public and private fields in a type that are marked by the SerializableAttribute are serialized by default", without referring to static fields specifically. Is there documentation to support the fact that static fields are not serialized? – ALEXintlsos Mar 18 '14 at 18:25
  • 2
    @ALEXintlsos: The whole concept of serialization is to serialize an instance. It wouldn't make sense to store static fields. – SLaks Mar 18 '14 at 18:28
  • @SLaks Is an object no longer an object when it is static? I can see your argument that you wouldn't serialize the whole class with that, but the class itself is, in a manner of speaking, an object. It has a state that is, in an abstract sense, independent of its instances, with static fields and methods. While there is a sort of entity that defines the class, there is also an object that represents its state, and it would only make sense if that object could also be serialized. If there is another word for this, please let me know, because I can't think of anything more appropriate. – Gurgadurgen Jun 17 '14 at 20:23
  • 1
    @Gurgadurgen: No; the class is not an object. In .Net terms, "object" means an instance of a class. You're right that static fields do occupy memory. – SLaks Jun 17 '14 at 23:10
  • @SLaks in the sense of OOP, no, a class is not an object. However, in terms of the CLR, and taking a step back from OOP, an object can also just be a collection of data/methods, with no perception of what a "class" is. This is a bit closer to the way that classes are represented in CLR memory, as far as I know, but I'm certainly no expert on the matter. My point, though, was that serialization is intended for storing/sending state data. Classes have state. It would make sense if they could be serialized. – Gurgadurgen Jun 18 '14 at 00:27