views:

29

answers:

1

I apologise for asking a question that's probably been asked hundreds of times before, but I don't seem to be able to find an answer in the archives; probably because my question is too basic.

I know that XML Serialization by default only touches public members and properties. Properties very often mask a private variable; particularly if they're readonly. Serializing these is fine; the value that the instance exposes to the world is what goes into the XML. But if Deserialization of the same data can't put the value back where it belongs, what's the point of doing it? Is there something I'm missing about how XML Serialization is normally used for classes with masking properties? Surely it can't be that the only answer is explicitly implementing Read/WriteXML - because that's more effort than it's worth!

+3  A: 

You're right, but I think you lost the overview over all implications. ;-) If you explicitly define, that a property cannot be written, it's obvious that you cannot deserialize it. At least not in the default way. You have different options to solve that:

  • Obviously you want to write to the property, so you should think about making it writable. From time to time it is good not to be too paranoid.

  • Most cases where a property really has to be readonly is in case of calculated properties. But these do not need to be serialized at all. So mark them with XmlIgnore and you're done.

  • You can pass overrides to the XmlSerializer. Don't know out of my head how powerful they are, but you might have a look at the documentation. Usually they are used to modify serialization behavior of types you cannot modify (ie. cannot add attributes).

  • If the above solutions do not work, you might have to implement Read/WriteXml.

Achim
I suppose you're correct - I am *extremely* paranoid about misuse of my classes. Nothing is exposed to the world as writeable if manipulating it could possibly screw up the state of the instance. My reservations are probably due to me experimenting with a toy model instead of a production implementation - and not seeing the actual utility.
Tom W