I am currently trying to serialize / deserialize (version 2.0.0.668) an array of objects where each object is a derrived type. The hierarchy, for simplicity, is as follows:
[ProtoContract]
[ProtoInclude(1, typeof (DeviceDescriptor1))]
[ProtoInclude(2, typeof (DeviceDescriptor1))]
public interface IDeviceDescriptor
{
}
[ProtoContract]
public sealed class DeviceDescriptor1
: IDeviceDescriptor
{
[ProtoMember(3)]
public int Foo { get; set; }
}
[ProtoContract]
public sealed class DeviceDescriptor2
: IDeviceDescriptor
{
[ProtoMember(4)]
public int Bar { get; set; }
}
The following test code first serializes an array, then deserializes it again:
var devices = new IDeviceDescriptor[]
{
new DeviceDescriptor1{Foo = 1},
new DeviceDescriptor2{Bar=42},
};
using (var stream = new MemoryStream())
{
Serializer.Serialize(stream, devices);
stream.Position = 0;
var actualDevices = Serializer.Deserialize<IDeviceDescriptor[]>(stream);
}
However upon deserialization, a ProtoException is thrown: The type cannot be changed once a serializer has been generated for ProtoBuf.DeviceDescriptor1 (ProtoBuf.IDeviceDescriptor)
I stumbled upon an older question of similar nature (In Protobuf-net how can I pass an array of type object with objects of different types inside, knowing the set of potential types in advance), but I am unsure if this one still applies - nearly 4 years later.
I am not sure what I am doing wrong here. Is this case unsupported? If so, what are my options to solve this particular problem?
Any help is appreciated :)
edit
This is the workaround for this particular problem that I came up with: Instead of serializing an array of abstract types, I serialize a generic type 'ProtobufFrame' (with one field of type T) which in this particular case ends up being 'ProtobufFrame'.