views:

105

answers:

2

Hi

I'm testing XML Serialization in my class, but i noticed that the ID number didn't get saved when i ran the program.

So i was looking around and modifying a few things but nothing worked, then i saw that all fields except ID had both get and set properties. So i added a set; property to my ID number and poof it worked. The question is, does it have to be set; and get; function on all my properties for XML Serialization to work?

I don't want the ID number to be modified after the object has been created (its automatically generated).

+3  A: 

Yes, this is basically a restriction of XML serialization. From the XML Serialization docs:

Only public properties and fields can be serialized. Properties must have public accessors (get and set methods). If you must serialize non-public data, use the BinaryFormatter class rather than XML serialization.

XML serialization isn't as flexible as one might like.

Jon Skeet
I noticed he didn't mention which version of the framework he was using. Wasn't this changed in .NET 3.5?
Justin Niessner
@Justin - not AFAIK.
Marc Gravell
While it may be a verbatim quote from MSDN, I wouldn't necessarily advocate BinarySerializer as an alternative for those scenarios where xml was the previous option...
Marc Gravell
A: 

Note that if you want to serialize non-public data as xml, DataContractSerializer might be useful. It isn't as flexible as XmlSerializer (and you can't specify attributes), but it can serialize non-public data:

[DataContract]
public class Person {
    [DataMember]
    private int id;

    public int Id {get {return id;}} // immutable

    public Person(int id) { this.id = id; }

    [DataMember]
    public string Name {get;set;} // mutable
}

Note also that it doesn't use your constructor... or indeed any constructor - it cheats, allowing it to create an object and fill the data in afterwards.

Marc Gravell