I have a deserialization method (decorated with the [OnDeserialized()] attribute) which I want to override in a derived class. When I try to do so, I get the following runtime error:
An unhandled exception of type 'System.TypeLoadException'.... Type 'BaseObj' in assembly ... has method 'OnDeserialization' which is either static, virtual, abstract or generic, but is marked as being a serialization callback method.
I couldn't find any documentation confirming this restriction on serialization callbacks (other than the error message itself). Can anyone explain this strange limitation?
Based on a suggestion in a comment here, I resorted to calling a separate virtual function from the OnDeserialization method, like so:
[Serializable()]
public class BaseObj
{
protected string obj { get; set; }
[OnDeserialized()]
public void OnDeserializedMethod(StreamingContext context)
{
//call the virtual method because deserialization callbacks can’t be virtual
onDeserialized(context);
}
virtual protected void onDeserialized(StreamingContext context)
{
obj = "This value was deserialized by the base class.";
}
}
[Serializable()]
public class DerivedObj : BaseObj
{
override protected void onDeserialized(StreamingContext context)
{
obj = "This value was deserialized by the derived class.";
}
}
This seems to work fine, but it seems rather "kludgey". Is this really my only option? Why can't a serialization callback method be virtual?