I was reading custom serialization article on msdn: http://msdn.microsoft.com/en-us/library/ty01x675%28VS.80%29.aspx
It mentions that there are two ways of implementing custom serialization:
1, using OnDeserializedAttribute, OnDeserializingAttribute, OnSerializedAttribute, OnSerializingAttribute
2, implement ISerializable interface
According to MSDN, method #1 is "best practice and easiest", but I fail to understand how are the two methods even the same thing. To my understanding, the OnSerializing|OnSerialized|etc attributes allow you to hook methods to particular phases of the serialization, while ISerializable interface allows you to directly modify what goes into and comes out of SerializationInfo. Is this correct?
To put my confusion into context, how do you implement OnSerializing to serialize object field under different name? like the following code:
public virtual void GetObjectData(SerializationInfo info, StreamingContext context)
{
info.AddValue("i", n1);
info.AddValue("j", n2);
info.AddValue("k", str);
}
Update: Although Frederik Gheysels's answer is not completely correct (decorating with Serializable is pre-requisite for both OnSerializing/OnDeserializing attributes and ISerializable interface), he did however points out that OnSerializing/OnDeserializing attributes are meant to be supplement of ISerializable, so I am accepting his answer on this point.