Search code examples
c#xmlserializationxmlserializer

C#: What members will be serialized to XML element when making a class [Serializable]


Given a class marked as [Serializable], how to we know whether the member of it will be serialized or not (the member has no attribute) by XmlSerializer?

For example:

[Serializable]
public class C2
{
    public int x1 = 1;
    private int x2 = 2;
    public static int x3 = 3;
    public readonly int x4 = 4;

    public int Y1 { get; set; }
    public static int Y2 { get; set; }
}

We have a class C2, and after serialized a new object C2 c = new C2() into XML string, I found that only x1 and Y1 are serialized. So I infer that:

  1. public field and property will be serialized.
  2. private field and property will not be serialized.
  3. static and readonly field and property will not be serialzed.
  4. MethodInfo will not be serialized.
  5. ...

My question is that is there any guidelines to know that: without marking any attribute to a member of class, how do we know that this member will be serialized or not?


Solution

  • Since XML serialization does not use SerializableAttribute there is no difference in what properties will be serialized to XML with or without [Serializable] on the class (see What is [Serializable] and when should I use it? for reasons to use it).

    You seem to already correctly got list of what is serialized from Introducing XML Serialization:

    XML serialization serializes only the public fields and property values of an object into an XML stream. XML serialization does not include type information.