Joseph Nields
Joseph Nields

Reputation: 5661

Can you deserialize an instance of an interface without its type definition?

Let's say I have a serialized bytes of an instance of an interface, AnInterface, like so:

AnInterface instance = new ConcreteClass();
serializeToDatabase(instance);

Is it possible to do something like:

IFormatter formatter = new BinaryFormatter();
MemoryStream stream = new MemoryStream();
byte[] bytes = bytesSavedToDB;
stream.Write(bytes, 0, bytes.Length);
stream.Position = 0;
AnInterface instance = (AnInterface) formatter.Deserialize(stream);

without having the definition for ConcreteClass?

Upvotes: 2

Views: 167

Answers (2)

alex
alex

Reputation: 12654

BinaryFormatter saves information about the types into the binary stream. It uses that information to reconstruct the object graph during deserialization. So, you can deserialize the stream without knowing what object it contains.

However, all the concrete classes that were serialized should be loadable during deserialization. In practice, this means that the assemblies that hold them should be either in the application folder, GAC, or loaded into memory by other means.

formatter.Deserialize returns just the object, that you can cast to an interface or to concrete type.

Upvotes: 2

Younes
Younes

Reputation: 4823

You can not deserialize this without knowing the (real) type of the class.

Upvotes: -1

Related Questions