Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Force XML serialization to serialize readonly property

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?

like image 241
Chris Avatar asked Apr 07 '11 17:04

Chris


1 Answers

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:

/// <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");     } } 
like image 160
Justin Avatar answered Oct 16 '22 23:10

Justin