2

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.

image

Why? Serializable attribute is useless?

Hui Zhao
  • 655
  • 1
  • 10
  • 20
  • 2
    Yes it is useless. It is only used if, for example, you use BinaryFormatter or SoapFormatter, – EZI Jan 19 '15 at 18:59

1 Answers1

2

When working with the XmlSerializer, it is important that you mark your types with the [Serializable] attribut

That is not correct. Only some serializers rely on that attribute, but not XmlSerializer.

Note that there are a number of inconsistencies between the various serializers in the .NET framework. Some will call a default constructor/execute field initializers, some will not. Some will serialize private members, some will not. Some use SerializableAttribute, some do not.

How does WCF deserialization instantiate objects without calling a constructor?

Read up on the specifics of the serializer you are using to avoid surprises.

Community
  • 1
  • 1
Eric J.
  • 147,927
  • 63
  • 340
  • 553