Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is implementing ISerializable interface necessary when not implementing any custom serialization/deserialization

I am looking at a class in a solution that implements the ISerializable interface. It has a GetObjectData method for serialization as required by the interface. There is not any custom serialization happening here, it is simply populating the SerializationInfo object with the names of the properties of the class and their values.

[Serializable]
public class PersonName :ISerializable
{
    [DataMember]
    public string NamePrefix { get; set; }
    [DataMember]
    public string GivenName { get; set; }
    [DataMember]
    public string SurName { get; set; }

    public PersonName(string givenName, string surName, string namePrefix)
    {
        GivenName = givenName;
        SurName = surName;
        NamePrefix = namePrefix;
    }

    public PersonName()
    {
    }

    #region ISerializable Members

    public void GetObjectData(SerializationInfo info, StreamingContext context)
    {
        info.AddValue("NamePrefix",NamePrefix);
        info.AddValue("GivenName",GivenName);
        info.AddValue("SurName",SurName);
    }
}

From the documentation I've read so far, as I understand it, this is what would happen anyway by the class being marked with the [Serializable] attribute, and as you can see the class does not have a deserialization constructor, which is why I'm looking at it to begin with. From what I can tell, rather than needing to add the deserialization constructor to the class, the class really doesn't need to implement the ISerializable interface in the first place. Is that correct?

like image 482
jaywon Avatar asked Jan 19 '12 20:01

jaywon


1 Answers

the class really doesn't need to implement the ISerializable interface in the first place. Is that correct?

Correct. Implementing ISerializable is when you need to do something other than the default serialization behavior. The [Serializable] attribute should be enough.

like image 193
vcsjones Avatar answered Sep 30 '22 04:09

vcsjones