In C#, I have a class which has a derived property that should be serialized via XML. However, XML serialization (by default) doesn't serialize read=only properties. I can work around this by defining an empty setter like so:
public virtual string IdString
{
get { return Id.ToString("000000"); }
set { /* required for xml serialization */ }
}
But is there a cleaner more semantically correct way, short of writing my own ISerializable implementation?
Honestly this doesn't seem too bad to me as long as it is documented
You should probably throw an exception if the setter is actually called:
To take the solution a little further to allow deserialization to work as well...
This will allow
Id
to be set exactly one time to a value greater than or equal to 0. Any attempts to set it after will result inInvalidOperationException
. This means thatXmlSerializer
will be able to setId
during deserialization, but it will never be able to be changed after. Note that if the property is a reference type then you can just check for null.This may not be the best solution if you have a lot of read-only properties to serialize/deserialize as it would require a lot of boilerplate code. However, I've found this to be acceptable for classes with 1-2 read-only properties.
Still a hack, but this is at least a little more robust.
In short, no. With
XmlSerializer
you can either implementIXmlSerializable
(which is non-trivial), or write a basic DTO (that is fully read-write) and then translate from the DTO model to your main model.Note that in some cases
DataContractSerializer
is a viable option, but it doesn't offer the same control over the XML. However, with DCS you can do: