I have a class with some collections in them, and I would like to serialize instances of this class to XML without having to initialize the collections to be empty, and without having to implement IXmlSerializable. I don't care if it creates empty elements, or doesn't create the elements at all. Just that it works without having to initialize a collection for each collection based property.
I have look at all the XML attributes I can decorate the properties with, and have not had any success with this. This seems like a simple thing to do that is can have an element or just none at all. Then when it is being deserialized it would just leave them null or ignore them period.
Here is a simple version of a class to use for working through this issue. Using this and the defaults you get an exception "Object reference not set to an instance of an object" due to the collections being null;
public class MyClass
{
public string Name { get; set; }
public bool IsAlive { get; set; }
public List<Car> Cars { get; set; }
public List<Home> Homes { get; set; }
public List<Pet> Pets { get; set; }
public void ToXmlFile(string fileName)
{
XmlSerializer serializer = new XmlSerializer(typeof(MyClass));
TextWriter writer = new StreamWriter(fileName);
serializer.Serialize(writer, this);
writer.Close();
}
}
EDIT Thanks for the helps guys, it turns out the issue was in my GetHashCode method which didn't handle the null correctly. Once I fixed this all was good. I marked the first one to answer as being correct. Sorry for the Red Herring, but working through it with you guys did help.