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?