I am using XmlSerializer to serialize a List of objects of a class that also have some List objects.
public class Configuration
{
private IList<Project> _projects = null;
public IList<Project> Projects
{
get
{
return new List<Project>(_projects);
}
set
{
_projects = value;
}
}
public void Load()
{
//Here takes place the deserialization
}
public void Save()
{
//Here takes place the serialization
}
}
public class Project
{
public string Name { get; set; }
private IList<Document> _documents = null;
public IList<Document> Documents
{
get
{
return new List<Document>(_documents);
}
set
{
_documents = value;
}
}
private IList<Test> _tests = null;
public IList<Test> Tests
{
get
{
return new List<Test>(_tests);
}
set
{
_tests = value;
}
}
}
This implementation does not work throwing an exception at runtime about Documents or Tests variable being of an interface type (IList, a detail that seems not to be a problem with Projects). If I change Documents and Tests to List, then the exception is gone, but another problem arises (not related). Serialization does not serialize the Documents and Tests arrays (and thus deserialization cannot restore those variables). If I change the custom get implementation for both properties, returning _documents and _tests directly, it all works as expected. But again, Projects property also has a custom get implementation and it works as expected.
public class Configuration
{
private IList<Project> _projects = null;
public IList<Project> Projects
{
get
{
return new List<Project>(_projects);
}
set
{
_projects = value;
}
}
public void Load()
{
//Here takes place the deserialization
}
public void Save()
{
//Here takes place the serialization
}
}
public class Project
{
public string Name { get; set; }
public List<Document> Documents { get; set; }
public List<Test> Tests { get; set; }
}
Of course I can live with this but I suspect that I may be doing something wrong. First I see no reason why I can serialize Projects being a IList and not Documents nor Tests. Secondly I see no reason why the custom gettter for Projects works, but it is preventing de correct serialization of Documents and Tests.
I also tried to use DataContractSerializer and it works out of the box but I prefer the clearer xml output from XmlSerializer.
Any hints?
P.S.: A full VS 2015 solution with the complete implementation and tests can be downloaded in the following link: https://www.dropbox.com/s/38cp12rgi2o4pqw/SerializationTest.zip?dl=0