views:

538

answers:

5

Hi folks, what's the difference between using the Serializable attribute and implementing the ISerializable interface?

Please clarify.

TIA

+5  A: 

The SerializableAttribute instructs the framework to do the default serialization process. If you need more control, you can implement the ISerializable interface. Then you would put the your own code to serialize the object in the GetObjectData method and update the SerializationInfo object that is passed in to it.

Segfault
If you implement ISerializable, it is also customary (or possibly even required) to implement the deserialization constructor: protected SomeClass(SerializationInfo info, StreamingContext context)
jrista
Note that you still have to mark the class [Serializable] even if you implement ISerializable interface.
Anna Lear
A: 

ISerialize force you to implement serialization logic manially, while marking by Serializable attribute (did you mean it?) will tell Binary serializer that this class can be serialized. It will do it automatically.

Andrey
yes, that's what i meant.
SoftwareGeek
A: 

Inheriting from ISerializable allows you to custom implement the (de)serialization. When using only the Serializable attribute, the (de)serialization can be controlled only by attributes and is less flexible.

logicnp
Deserialization is handled via the deserialization constructor. See my comment on segfaults answer.
jrista
A: 

ISerializable Interface lets you implement Custom Serialization other than default. When you implemet ISerializable interface, you have to override GetObjectData method as follows

public void GetObjectData (SerializationInfo serInfo, 
                                    StreamingContext streamContext)
{
   // Implement custom Serialization
}
Asad Butt
+2  A: 

When you use the ISerialize 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', there would be a finer degree of control over the serializing of the data.

See here for an example of a custom serialization here on SO. This example shows how to keep the serialization backwards compatible with different versionings of the serialized data.

Hope this helps, Best regards, Tom.

tommieb75