When using read-only fields in a serializable class, that should not be serialized (or don't need to): How can they be restored? Assume the following piece of code:
[Serializable]
class SerializableClass
{
[NonSerialized]
private readonly object someLock = new object();
[OnDeserializing]
private void restore(StreamingContext sc)
{
// cannot one-time-access readonly fields (like in a
// constructor or shortcut like above), too sad...
// someLock = new object();
}
// ...
}
I came across this problem having some objects for locking (that are exclusively used for locking) that are always private readonly
(and which I think don't have a place in the serialized representation). As a workaround I am asking myself:
- Should these objects better not be read-only, so that they can be restored?
- Should I instead include them to be serialized (as long these are only some 'empty objects' anyway)?
But there might be a more general solution for the use of read-only fields, e.g.:
- Is there a way of implementing a deserializing constructor that gets called (like when implementing
ISerializable
) without loosing the automatic serialization of the fields?
Thanks a lot in advance.