I am trying to serialize a type like follows:
public UsersPanel(UsersVM userVm)
{
var serialized = Serialize(userVm);
}
public static string Serialize(ViewModelBase instance)
{
var formatter = new BinaryFormatter();
using (var stream = new MemoryStream())
{
formatter.Serialize(stream, instance); // breaks here
return Convert.ToBase64String(stream.ToArray());
}
}
Where UsersVM is defined as
public class UsersVm : ViewModelBase {}
and ViewModelBase is defined as
[Serializable]
public class ViewModelBase {}
This is giving me the following error:
Type ‘UsersVM’ is not marked as serializable.
Why is it telling me this, if I’ve cast the object userVm to ViewModelBase (which is marked as Serializable) by passing it into Serialize(ViewModelBase instance)?
I would have thought that passing UsersVM would be replaced by the base type ViewModelBase when passing it into the method which takes ViewModelBase.
How can I serialize ViewModelBase?
Solving the Issue
You have to mark your derived class as serializable, too
Why you have to do this
The BinaryFormatter looks at the actual type of the object instance when serializing. The cast just tells the compiler to treat the instance as if it were a different type but does not actually change the instance into that type.
Side Note
I initially read the question backwards and found the answer to the inverse question interesting and potentially useful to others…
Note if the situation were reversed (the base class were not marked serializable and you didn’t have access to the source code), you could still accomplish your goal.
http://msdn.microsoft.com/en-us/magazine/cc163902.aspx#S14
The article provides a code sample including a utility to help implement this approach.