ISerializable for Collection<T>

360 Views Asked by At

I am writing the serialization code for a Collection<T> class and would like to know how to set and get the items in the collection. I am using Binary serialization.

I have made an attempt in the following code, but am not sure on the correct approach.

Here is my code:

[Serializable]
public class EmployeeCollection<Employee> : Collection<Employee>, ISerializable
{
    public int EmpId;
    public string EmpName;
    public EmployeeCollection()
    {
        EmpId = 1;
        EmpName = "EmployeeCollection1";
    }
    public EmployeeCollection(SerializationInfo info, StreamingContext ctxt)
    {
        EmpId = (int)info.GetValue("EmployeeId", typeof(int));
        EmpName = (String)info.GetValue("EmployeeName", typeof(string));
        //Not sure on the correct code for the following lines
        var EmployeeCollection = (List<Employee>)info.GetValue("EmployeeCollection", typeof(List<Employee>));
        for (int i = 0; i < EmployeeCollection.Count; i++)
        {
            this.Add(EmployeeCollection[i]);
        }
    }

    public void GetObjectData(SerializationInfo info, StreamingContext ctxt)
    {
        info.AddValue("EmployeeId", EmpId);
        info.AddValue("EmployeeName", EmpName);
        //Not sure on the correct code for the following lines
        var EmployeeCollection = new List<Employee>();
        for (int i = 0; i < this.Count; i++)
        {
            EmployeeCollection.Add(this[i]);
        }
        info.AddValue("EmployeeCollection", EmployeeCollection);
    }

In the GetObjectData method, the List<Employee> is added to the SerializationInfo successfully. However, in the EmployeeCollection method, the List<Employee> has a null entry for each item added.

How can I correctly serialize and deserialize the items in a Collection<T> class when implementing the ISerializable interface?

1

There are 1 best solutions below

2
On

Rather than taking the time to write custom serialization required for BinaryFormatter, try out AnySerializer. You don't need to write any serialization code, and support for generic collections is built-in. You can omit the [Serializable] attribute, and get rid of the ISerializable interface. If it works for you, let me know as I am the author.

A working example:

public class EmployeeCollection<Employee> : Collection<Employee>
{
    public int EmpId;
    public string EmpName;
    public EmployeeCollection()
    {
        EmpId = 1;
        EmpName = "EmployeeCollection1";
    }
}

// serialize/deserialize
using AnySerializer;

var collection = new EmployeeCollection();
var bytes = Serializer.Serialize(collection);
var restoredCollection = Serializer.Deserialize<EmployeeCollection<Employee>>(bytes);