Protobuf-net deserializes empty collection to null when the collection is a property of another type
Ultimately, this comes down to the fact that the protobuf specification has no concept of null
, and no way of expressing null
. A collection is really just a repeated
block (from the .proto specification); and a repeated
block of 0 items is nothing whatsoever; no bytes; nothing. Since the collection member itself does not appear in protobuf, there is nowhere to say whether that thing is null vs not-null.
In xml terms, if is like using [XmlElement]
to embed child items inside a parent (rather than [XmlArray]
/ [XmlArrayItem]
- i.e.
<Foo>
<Name>abc</Name>
<Item>x</Item>
<Item>y</Item>
<Item>z</Item>
</Foo>
Here, a Foo
with 0 Item
s would be:
<Foo>
<Name>abc</Name>
</Foo>
from which, it is impossible to say whether the collection itself was null
vs empty. Obviously protobuf isn't actually xml, but the above is meant purely as an illustrative example.
So: protobuf has no way to express this scenario, and therefore neither does protobuf-net.
In the other scenario you represent: the serialized representation of an empty list (as the root element) is: zero bytes. When you deserialize, if it finds the stream is empty, it always returns a non-null value as the root object, that being the most likely version of what you wanted.