XML serialization is handy, but it does lack some power. For example, if you have class inheritance, and you want a property of the child class to have a different name than the one given to it by the parent, you will get an error at run-time when trying to serialize the object: "Member 'Derived.Name' hides inherited member 'Base.Name', but has different custom attributes.".
Assume you have a class structure like this:
public abstract class Base
{
private int id;
private string name;
[XmlElement("id")]
public int Id
{
get { return id; }
set { id = value; }
}
[XmlElement("name")]
public virtual string Name
{
get { return name; }
set { name = value; }
}
}
public class Derived : Base
{
[XmlElement("newName")]
public override string Name
{
get { return base.Name; }
set { base.Name = value; }
}
}
To see the error, call it like this:
static void Main(string[] args)
{
Derived d = new Derived();
d.Id = 23;
d.Name = "Dan";
string xml = GetXMLFromObject(d);
Console.WriteLine(xml);
}
Download the sample application here to play with it.