Reputation: 2790
I'm using protobuf-net r278 in C#, and I just noticed that if I have a class with an int
field, the field isn't deserialized properly if it's value is set to 0. Namely, when deserialized it gets its default value from the class definition. Example class:
[ProtoBuf.ProtoContract]
public class
Test
{
[ProtoBuf.ProtoMember(1)]
public int Field1 = -1
[ProtoBuf.ProtoMember(2)]
public int Field2 = -1;
}
Then run this code:
var test = new Test();
test.Field1 = 0;
test.Field2 = 0;
MemoryStream ms_out = new MemoryStream();
ProtoBuf.Serializer.Serialize(ms_out, test);
ms_out.Seek(0, SeekOrigin.Begin);
var deser = ProtoBuf.Serializer.Deserialize<Test>(ms_out);
When I do this, deser
has Field1 = -1
and Field2 = 2
, not 0's. Am I doing something wrong here?
Upvotes: 2
Views: 1148
Reputation: 1062492
In line with the wire-spec, there is an implicit zero default (which can be changed to other values with [DefaultValue(...)]
. You can tell it to behave itself as you want by setting IsRequired = true
in the attribute:
[ProtoBuf.ProtoMember(1, IsRequired = true)]
Upvotes: 5