I’m using the V2 of proto-buf. When I serialize a sample project with 2 classes, proto-buf serializes when I don’t include [ProtoMember(x)] in the fields. I just put [ProtoContract] before the classes. I don’t know why this is happening?
When I tried to serialize my real project after putting [ProtoContract] before all the classes and not adding [ProtoMember(x)] for any fields in any classes, I don’t get an error but the serialized file is empty (0 bytes). Does anyone know what is happening? Do we need to put protomember before every field in order to serialize? If so, why did my sample project get serialized without using any protomember in the project?
My real project has about like 20-30 classes with each having a lot of fields? Do I need to put protomember in all the fields in all the classes?
Thanks for your insight.
Serializing an object with no interesting fields to write is not an error as such – pretty unusual, but not strictly an error – so indeed: it doesn’t complain. Zero bytes is a valid serialization length for protobuf, even with fields to serialize (if they all turn out to be null/default-value/conditional-and-disabled/etc). Actually, this came up earlier this week because the new MS WebAPI assumes (incorrectly in this case) that a payload length of zero bytes is impossible, and so doesn’t invoke the deserializer. Sigh.
But to answer your question!
If you are absolutely sure you aren’t going to change your DTOs, you can ask protobuf-net to make up the numbers; this is “ImplicitFields”, and can be done either as:
The one issue with ImplicitFields is that: the numbers it generates are essentially the contract. ImplicitFields generates the numbers by ordering alphabetically and just using consecutive numbere. If you change your DTO (add/remove/rename a member) it could start thinking of different numbers, which is a breaking change: any old data on disk / in a database / etc may fail to deserialize correctly.
If you are sure your contract is fixed, you can enable this via (apologies if I get it a tiny bit wrong – not at a PC):
Of course, you can always change this to explicit
[ProtoMember(n)]later – just use 1, 2, 3 etc as per the alphabetical member layout, and then make any changes you want to your DTO.