views:

67

answers:

1

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?

+1  A: 

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)]
Marc Gravell
thanks, exactly what I needed.
toasteroven