Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What's the difference between using the Serializable attribute & implementing ISerializable?

What's the difference between using the Serializable attribute and implementing the ISerializable interface?

like image 775
SoftwareGeek Avatar asked Mar 02 '10 17:03

SoftwareGeek


People also ask

What does serializable attribute do?

Allows an object to control its own serialization and deserialization.

What happens if we don't use serializable?

What happens if you try to send non-serialized Object over network? When traversing a graph, an object may be encountered that does not support the Serializable interface. In this case the NotSerializableException will be thrown and will identify the class of the non-serializable object.

Why should I use serialization?

Well, serialization allows us to convert the state of an object into a byte stream, which then can be saved into a file on the local disk or sent over the network to any other machine. And deserialization allows us to reverse the process, which means reconverting the serialized byte stream to an object again.


1 Answers

When you use the SerializableAttribute attribute you are putting an attribute on a field at compile-time in such a way that when at run-time, the serializing facilities will know what to serialize based on the attributes by performing reflection on the class/module/assembly type.

[Serializable] public class MyFoo { … } 

The above indicates that the serializing facility should serialize the entire class MyFoo, whereas:

public class MyFoo {     private int bar;      [Serializable]     public int WhatBar     {        get { return this.bar; }     } } 

Using the attribute you can selectively choose which fields needs to be serialized.

When you implement the ISerializable interface, the serialization effectively gets overridden with a custom version, by overriding GetObjectData and SetObjectData (and by providing a constructor of the form MyFoo(SerializationInfo info, StreamingContext context)), there would be a finer degree of control over the serializing of the data.

See also this example of a custom serialization here on StackOverflow. It shows how to keep the serialization backwards-compatible with different versionings of the serialized data.

Hope this helps.

like image 87
t0mm13b Avatar answered Sep 20 '22 19:09

t0mm13b