Help needed for the most trivial example of protobuf-net

Observe the following trivial code snippet:

  [ProtoContract]
  public class B
  {
    [ProtoMember(1)] public int Y;
  }

  [ProtoContract]
  public class C
  {
    [ProtoMember(1)] public int Y;
  }

  class Program
  {
    static void Main()
    {
      var b = new B { Y = 2 };
      var c = new C { Y = 4 };
      using (var ms = new MemoryStream())
      {
        Serializer.Serialize(ms, b);
        Serializer.Serialize(ms, c);
        ms.Position = 0;
        var b2 = Serializer.Deserialize<B>(ms);
        Debug.Assert(b.Y == b2.Y);
        var c2 = Serializer.Deserialize<C>(ms);
        Debug.Assert(c.Y == c2.Y);
      }
    }
  }

The first statement fails! Each Serialize statement advances the position of the stream by 2, so at the end of ms.Position it is 4. However, after the first Deserialize statement, the position is set to 4, not 2! In fact, b2.Y is 4, which should be the value of c2.Y!

There is something absolutely basic that I'm missing here. I am using protobuf-net v2 r383.

Thank.

EDIT

It must be something really stupid, because it doesn't work in v1 either.

+1
source share
1 answer

You need to use the SerializeWithLengthPrefix / DeserializeWithLengthPrefix methods to extract a single object from the stream. this should work:

var b = new B { Y = 2 };
var c = new C { Y = 4 };
using (var ms = new MemoryStream())
{
    Serializer.SerializeWithLengthPrefix(ms, b,PrefixStyle.Fixed32);
    Serializer.SerializeWithLengthPrefix(ms, c, PrefixStyle.Fixed32);
    ms.Position = 0;
    var b2 = Serializer.DeserializeWithLengthPrefix<B>(ms,PrefixStyle.Fixed32);
    Debug.Assert(b.Y == b2.Y);
    var c2 = Serializer.DeserializeWithLengthPrefix<C>(ms, PrefixStyle.Fixed32);
    Debug.Assert(c.Y == c2.Y);
}
+2

All Articles