XML serialization syntax for serializing readonly property

In C #, I have a class that has a derived property that needs to be serialized through XML. However, XML serialization (by default) does not serialize read = only properties. I can get around this by setting an empty setter as follows:

public virtual string IdString { get { return Id.ToString("000000"); } set { /* required for xml serialization */ } } 

But is there a cleaner, semantically correct way, not to mention my own implementation of ISerializable?

+26
c # xml-serialization
Apr 07 '11 at 17:50
source share
3 answers

Honestly, this doesn't seem too bad for me if it's documented

You should probably throw an exception if the setter is actually being called:

 /// <summary> /// Blah blah blah. /// </summary> /// <exception cref="NotSupportedException">Any use of the setter for this property.</exception> /// <remarks> /// This property is read only and should not be set. /// The setter is provided for XML serialisation. /// </remarks> public virtual string IdString { get { return Id.ToString("000000"); } set { throw new NotSupportedException("Setting the IdString property is not supported"); } } 
+16
Apr 08 '11 at 7:50
source share

In short, no. Using the XmlSerializer you can either implement IXmlSerializable (which is nontrivial) or write a basic DTO (which is fully read-write), and then transfer from the DTO model to your main model.

Note that in some cases, the DataContractSerializer is a viable option, but it does not provide the same control over XML. However, with DCS, you can:

 [DataMember] public int Id { get; private set; } 
+11
Apr 07 2018-11-18T00:
source share

To make the decision a little further so that deserialization also works ...

 public class A { private int _id = -1; public int Id { get { return _id; } set { if (_id < 0) throw new InvalidOperationException("..."); if (value < 0) throw new ArgumentException("..."); _id = value; } } } 

This will allow Id set exactly once a value greater than or equal to 0. Any attempts to set it after this will result in an InvalidOperationException . This means that the XmlSerializer will be able to set the Id during deserialization, but after that it can never be changed. Note that if the property is a reference type, you can simply check for null.

This may not be the best solution if you have many read properties for serialization / deserialization, as this will require a lot of template code. However, I have found that this is acceptable for classes with 1-2 read-only properties.

Still hacking, but it is at least a little more reliable.

+1
Jan 15 '16 at 19:18
source share



All Articles