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.
Nathan Phetteplace Jan 15 '16 at 19:18 2016-01-15 19:18
source share