kevin kevin - 5 months ago 20
C# Question

What is [Serializable] and when should I use it?

I found out that some classes use the


  • What is it?

  • When should I use it?

  • What kinds of benefits will I get?


What is it?

When you create an object in a .Net framework application, you don't need to think about how the data is stored in memory. Because .Net framework takes care of that for you. However, if you want to store the contents of an object to a file, send an object to another process or transmit it across the network, you do have to think about how the object is represented because you will need to convert it to a different format. This conversion is called SERIALIZATION.

Uses for Serialization

Serialization allows the developer to save the state of an object and recreate it as needed, providing storage of objects as well as data exchange. Through serialization, a developer can perform actions like sending the object to a remote application by means of a Web Service, passing an object from one domain to another, passing an object through a firewall as an XML string, or maintaining security or user-specific information across applications.

Apply the SerializableAttribute attribute to a type to indicate that instances of this type can be serialized. Apply the SerializableAttribute attribute even if the class also implements the ISerializable interface to control the serialization process.

All the public and private fields in a type that are marked by the SerializableAttribute are serialized by default, unless the type implements the ISerializable interface to override the serialization process. The default serialization process excludes fields that are marked with the NonSerializedAttribute attribute. If a field of a serializable type contains a pointer, a handle, or some other data structure that is specific to a particular environment, and cannot be meaningfully reconstituted in a different environment, then you might want to apply the NonSerializedAttribute attribute to that field.

See MSDN for more details.