Reputation: 679
I was trying to use protobuf-net and faced with the following problem. I have two classes.
[ProtoContract]
class parent
{
[ProtoMember(1)]
public string name { get; set; }
}
[ProtoContract]
class child : parent
{
[ProtoMember(2)]
public int num { get; set; }
}
If I create a child object without setting the child property "num"
var obj = new child() { name = "tester" };
and try to serialize it
using (var stream = new MemoryStream())
{
Serializer.NonGeneric.Serialize(stream, obj);
}
the stream will be empty.
Is there any way to handle this situation without using the attribute [ProtoInclude] for the parent class?
I'm using protobuf-net v2 r480.
Thanks
Upvotes: 1
Views: 237
Reputation: 1062975
The correct answer here is to use ProtoInclude to tell it about the sub-type. Otherwise, it is only serializing relative to "child", and without any interesting data (zero does not count as interesting by default) a zero-length stream is the correct serialization. Protobuf does not preclude empty streams.
If you can't use ProtoInclude because the type is not known at compile-time, then you can use;
RuntimeTypeModel.Default[typeof(parent)]
.AddSubType(number, typeof(child));
Note that "number" must be accurately repeatable later on, else it won't deserialize correctly.
Upvotes: 1