yonan2236
yonan2236

Reputation: 13659

Serializable Class

How I can make Student class serializable? I'm reading this article but I do not know what is the right approach if I would implement it in the below scenario.

public class Student
{
    private string _studentNumber;
    private string _lastName;
    private string _firtName;
    private List<Subject> _subjects;

    public Student() { }

    public string StudentNumber
    {
        get { return _studentNumber; }
        set { _studentNumber = value; }
    }

    public string LastName
    {
        get { return _lastName; }
        set { _lastName = value; }
    }

    public string FirstName
    {
        get { return _firtName; }
        set { _firtName = value; }
    }

    public List<Subject> Subjects
    {
        get { return _subjects; }
        set { _subjects = value; }
    }
}

public class Subject
{
    private string _subjectCode;
    private string _subjectName;

    public Subject() { }

    public string SubjectCode
    {
        get { return _subjectCode; }
        set { _subjectCode = value; }
    }

    public string SubjectName
    {
        get { return _subjectName; }
        set { _subjectName = value; }
    }
}

Upvotes: 3

Views: 462

Answers (2)

Nikhil Agrawal
Nikhil Agrawal

Reputation: 48600

Usually i serialize to make a deep copy of my object without implementing IClonenable interface.

In your case you can use

[Serializable()]
public class Student
{
   // Your Class
}

make a extension method

public static class ExtensionMethod
{  
    public static T DeepClone<T>(this T element)
    { 
        MemoryStream m = new MemoryStream();
        BinaryFormatter b = new BinaryFormatter();
        b.Serialize(m, element);
        m.Position = 0;
        return (T)b.Deserialize(m);
    }
}

and call it like

yourclassobject.DeepClone();

Upvotes: 2

Marc Gravell
Marc Gravell

Reputation: 1064114

For BinaryFormatter, just add [Serializable] before the public class ....

For XmlSerializer, nothing; that should work fine assuming you want elements

For DataContractSerializer (a 3.0 class, strictly speaking), add [DataContract] to the class, and [DataMember] to the properties

For protobuf-net, you can use the DataContractSerializer attributes as long as each [DataMember] specifies a unique Order=, or you can use [ProtoContract] on the class, and [ProtoMember(n)] on each property, for unique n.

For JavaScriptSerializer (technically 3.5), nothing - it should work

For Json.NET, nothing - it should work

Other options would include implementing ISerializable or IXmlSerializable, but frankly: you don't need that.

Upvotes: 9

Related Questions