views:

946

answers:

1

I am only familiar with the basics of serialization, now I have a use for it. I have an existing reporting system with a ReportBase abstract class and multiple reports deriving from the base class. These each have different report parameters specified in the constructor and occasionally extra methods. Is it possible to serialize any of the derived classes and then later deserialize without knowing the derived class type.

Alternatively could I do something with reflection to achieve it. I will probably be storing the serialized objects to a database so could add the report class to another field I suppose.

+4  A: 

Yes, it's certainly possible to deserialize without knowing the actual type of the object. In fact, you don't need to know anything about the type in order to deserialize. Deserialization, in the binary sense, simply converts an array of bytes into the original type and returns the reference as object. You're free to cast this to any legal type for the instance afterwards.

For example, the following code will deserialize the stream into an object and convert the reference to a ReportBase type.

public static void Deserialize(Stream stream)
{
    BinaryFormatter formatter = new BinaryFormatter();
    object obj = formatter.Deserialize(stream);
    ReportBase report= (ReportBase) obj;
}

Note above that I said it's possible. In order for this to work, stream must point to a valid serialized instance of ReportBase derived class and that class must conform to the rules of serialization.

It's very easy to create a class which is intended to be, but is not serializable: http://blogs.msdn.com/jaredpar/archive/2009/03/31/is-it-serializable.aspx

JaredPar
Thanks I will give it a go. For some reason I was thinking Deserialize required the type, its been a while since I used it.
PeteT