protobuf-net: Failing to deserialize ReadOnlyCollection

702 Views Asked by At

I'm trying to serialize and deserialize a ReadOnlyCollection using protobuf-net. However an exception is thrown upon deserialization when protobuf-net attempts to cast a List into a ReadOnlyCollection.

        var roc = new ReadOnlyCollection<byte>(new byte[] {1, 2, 3});
        var ms = new MemoryStream();

        Serializer.Serialize(ms, roc);
        ms.Position = 0;
        var roc2 = Serializer.Deserialize<ReadOnlyCollection<byte>>(ms);

        Console.WriteLine( BitConverter.ToString( roc2.ToArray() ) );

Is there a way to keep this as a ReadOnlyCollection rather than serializing/deserializing as List? In the actual application, the ReadOnlyCollection is a part of an immutable object which I want to serialize, and would prefer to keep it as a ReadOnlyCollection.

1

There are 1 best solutions below

0
On

I think that protobuf-net only deserialize collections as List. You could:

var roc2aux = Serializer.Deserialize<List<byte>>(ms);
var roc2 = new ReadOnlyCollection<byte>(roc2aux);
Console.WriteLine( BitConverter.ToString( roc2.ToArray() ) );