How can I serialize a base object if the implementation object is not Serializable?

I am trying to serialize a type, for example:

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 gives me the following error:

The type "UsersVM" is not marked as serializable.

Why does this tell me this if I passed the userVm object to ViewModelBase (which is marked as Serializable) by passing it to Serialize(ViewModelBase instance) ?

I would think that passing UsersVM would be replaced by the base type ViewModelBase when passing it to a method that accepts ViewModelBase .

How can I serialize ViewModelBase?

+4
source share
1 answer

Solution

You should mark your derived class as serializable, too

 [Serializable] public class UsersVm : ViewModelBase {} 

Why you should do it

BinaryFormatter looks at the actual type of the instance of the object during serialization. The cast simply tells the compiler to process the instance as if it were of a different type, but does not actually change the instance to this type.

Side note

I initially read the question back and found the answer to the back question interesting and potentially useful to others ...

Please note that if the situation was canceled (the base class was not marked serializable, and you did not have access to the source code), you can still achieve your goal.

a subclass can implement ISerializable, use reflection to read and serialize the fields of base classes, and use reflection again to set these fields during deserialization

http://msdn.microsoft.com/en-us/magazine/cc163902.aspx#S14

This article provides sample code that includes a utility to help implement this approach.

+5
source

All Articles