GromHellscream
GromHellscream

Reputation: 111

Inherited class protobuf-net serialization

After serialization of inherited class C2 stream looks like that:

0x5a 0x03

0x08 0x97 0x01

0x08 0x96 0x01

I can't understand that is the first group of bytes (5a 03)? I believed its must be second and third only which are representing Z1 and Z2 values?

My code:

    [ProtoContract]
    class C1
    {
        [ProtoMember(1, DataFormat = DataFormat.Default)]
        public int Z1 { get; set; }
    }

    [ProtoContract]
    class C2 : C1
    {
        [ProtoMember(1, DataFormat = DataFormat.Default)]
        public int Z2 { get; set; }
    }      

    public static void Main()
    {
        MemoryStream stream = new MemoryStream();
        ProtoBuf.Meta.RuntimeTypeModel.Default.Add(typeof(C1), true).AddSubType(11, typeof(C2));
        C2 c2 = new C2() {Z1 = 150, Z2 = 151};           
        Serializer.Serialize(stream, c2);
    }

Upvotes: 2

Views: 393

Answers (1)

Marc Gravell
Marc Gravell

Reputation: 1063884

  • 0x5a = field-number 11, wire-type 2 (length prefixed) - this represents the inheritance via encapsulation of sub-classes as inner-messages
  • 0x03 = 3 (length of payload)
    • 0x08 = field 1, wire-type 0 (varint)
    • 0x97 0x01 = 151 (varint = little-endian using MSB as continuation)
  • 0x08 = field number 1, wire-type 0 (varint)
    • 0x96 0x01 = 150

which basically maps to (in .proto)

message C1 {
    optional int32 Z1 = 1;
    optional C2 c2 = 11;
}
message C2 {
    optional int32 Z2 = 1;
}

Upvotes: 2

Related Questions