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

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.

Leave a Comment