9

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.

NH.
  • 2,240
  • 2
  • 23
  • 37
Mark
  • 510
  • 1
  • 5
  • 18
  • Ooh, that's intriguing. *right now* I would have to say simply "no that won't work", but I can think of a few ways I could tweak it to *make* it work. It would be changes to the deserialization core, though. You might want to log this as a feature request on protobuf-net. – Marc Gravell Nov 24 '11 at 00:03
  • I've added an [issue](http://code.google.com/p/protobuf-net/issues/detail?id=254) for this and a possible fix but I forgot to change the issue type so it's listed as a defect. Doh! – Mark Nov 24 '11 at 18:45
  • I saw. Thanks. I will get to it, but please keep in mind that protobuf-net isn't my day job - so it might take a couple of days to get a proper look at it. – Marc Gravell Nov 24 '11 at 18:51
  • Thanks Marc, I've done a hack around in my code so no rush, although I think it would be cool. :) – Mark Nov 24 '11 at 19:03

1 Answers1

0

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() ) );
fuyangli
  • 21
  • 7