Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does "default" serialization in C# serialize static fields?

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.

like image 281
Mark LeMoine Avatar asked Oct 11 '10 01:10

Mark LeMoine


People also ask

Are static fields serialized in C#?

No; static fields are not serialized.

What is C# serialization?

Serialization in C# is the process of converting an object into a stream of bytes to store the object to memory, a database, or a file. Its main purpose is to save the state of an object in order to be able to recreate it when needed. The reverse process is called deserialization.

Why is serialization not good?

It is not future-proof for small changes If you mark your classes as [Serializable] , then all the private data not marked as [NonSerialized] will get dumped. You have no control over the format of this data. If you change the name of a private variable, then your code will break.

How can we avoid serialization?

To avoid Java serialization you need to implement writeObject() and readObject() method in your Class and need to throw NotSerializableException from those method.


1 Answers

No; static fields are not serialized.

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

like image 178
SLaks Avatar answered Sep 27 '22 17:09

SLaks