When working with the XmlSerializer
, it is important that you mark your types with the [Serializable
] attribute, part of the SerializableAttribute
class.
class Program
{
static void Main(string[] args)
{
XmlSerializer serializer = new XmlSerializer(typeof(Person));
string xml;
using (StringWriter stringWriter = new StringWriter())
{
Person p = new Person
{
FirstName = "John",
LastName = "Doe",
Age = 42
};
serializer.Serialize(stringWriter, p);
xml = stringWriter.ToString();
}
Console.WriteLine(xml);
using (StringReader stringReader = new StringReader(xml))
{
Person p = (Person)serializer.Deserialize(stringReader);
Console.WriteLine("{0} {1} is {2} years old", p.FirstName, p.LastName, p.Age);
}
Console.ReadLine();
}
}
[Serializable]
public class Person
{
public string FirstName { get; set; }
public string LastName { get; set; }
public int Age { get; set; }
}
As you can see, the Person
class is marked with Serializable
. All members of the type are automatically serialized if they don't opt out.
However if I remove the Serializable
attribute, the result is still same with it.
See the image.
Why? Serializable
attribute is useless?