Can I avoid adding additional fields to a class to store data which is needed only for deserialization/serialization?
Suppose I have some class:
[Serializable]
class MyClass {
[NonSerialized]
NonSerializableDataType myField;
SomeOtherDataType serializableTemporaryData;
[OnSerializing]
OnSerializing (StreamingContext context) {
// build serializableTemporaryData from myField
}
[OnDeserialized]
void OnDeserialized (StreamingContext context) {
// build myField from serializableTemporaryData
}
}
Is there any way to avoid having the serializableTemporaryData field in each object of MyClass? Can I, for example, make it static (possibly by changing my On… methods)?
Constraint: I cannot change the implementation of NonSerializableDataType.
Example: Suppose myField contains a handle to a resource. Then, on serialization, I must store some information on how to acquire the resource after de-serialization, but I cannot store the handle itself. If I wrap the handle into another class, then I have just shifted the problem to the wrapper class — I would ask the very same question for the wrapper class then.
If you need to control the serialization process, you should implement the
ISerializationinterface.No additional class just for serialization data, no fields pollution. The only potential problem is to watch for any serializable data derived from this class (overwrite
GetObjectData(...)if needed).More info: MSDN ISerializable