What's the difference between using the Serializable
attribute and implementing the ISerializable
interface?
Allows an object to control its own serialization and deserialization.
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.
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.
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 (and by providing a constructor of the form SetObjectData
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With