12

This method accepts as the last argument an integer, but I'm not sure I understand what I would use it for exactly.

Serializer.SerializeWithLengthPrefix(stream, object, PrefixStyle.Base128, [tag]);

The same holds true for the corresponding Deserialize method.

Is it just a way to tag messages to add some sort of "querying" capabilities on deserialization to filter out unwanted messages or does it have any other usages?

Simone
  • 3,607
  • 1
  • 31
  • 37

1 Answers1

10

Basically, it is an additional marker that can be (although does not have to be) used to note the "type" of the message being added, since the presumption (when using the *WithLengthPrefix approach) is that there are multiple messages in the same stream.

By being included, it also means that the entire composite stream is itself an entirely valid protobuf message.

Ways of using this:

  • you can serialize a List<Foo>, and then repeatedly deserialize (with-length-prefix) individual Foo items, or vice-versa
  • with a heterogeneous set of objects, you can use the Serializer.NonGeneric API to allow type-resolution based on the tag, i.e. the code equivalent of "if 1 then Invoice; if 2 then Order, if 3 then skip it, if 4 then Customer", etc - this is especially useful if using a NetworkStream as a message-sending device. This approach (using a different tag per type) allows you to read objects off the stream, and deserialize them correctly, without knowing in advance the type of the next message

It is possible to omit this if you want - just pass zero (IIRC). This will save (typically) a byte per message appended, but: it means that the stream is no longer a valid protobuf itself. It can still be read, of course, by passing zero when reading.

Marc Gravell
  • 1,026,079
  • 266
  • 2,566
  • 2,900
  • 1
    Why does including the tag make it a valid protobuf message? Can't you deserialize individual items in a list without the tag? – Simone Dec 22 '11 at 09:38
  • Also, type resolution using tag has to be carried out by the application code, right? – Simone Dec 22 '11 at 09:43
  • 3
    @Simone it makes the *composite* message a valid protobuf, because `repeated MessageType` (in .proto) is encoded as a sequence of "[tag][length][payload]...[tag][length][payload]". Hence with the tag it is a valid protobuf, and without: it isn't. Re type resolution; normally yes, since it is intentionally platform independent; however, protobuf-net does also include some *additional* support for including some limited type information on the wire. – Marc Gravell Dec 22 '11 at 11:21