protobuf-net: Beware of setting an optional int primitive to zero
Here’s another gotcha with protobuf-net, setting an optional int to 0 causes it the property to be skipped during serialization.
private int? _myProperty;
[ProtoBuf.ProtoMember(21022, IsRequired = false, Name = @"myProperty", DataFormat = ProtoBuf.DataFormat.TwosComplement)]
public int myProperty {
get { return _myProperty ?? default(int); }
set { _myProperty= value; }
}
[System.Xml.Serialization.XmlIgnore]
[System.ComponentModel.Browsable(false)]
public bool myPropertySpecified {
get { return _myProperty != null; }
set { if (value == (_myProperty == null)) _myProperty = value ? fillreportpolicy : (int?)null; }
}
private bool ShouldSerializemyProperty() { return myPropertySpecified; }
private void ResetmyProperty() { myPropertySpecified = false; }
After you set myProperty to “0″, you’ll notice that myPropertySpecified will return true. You can also use reflection to verify that the property is indeed set. But, it won’t get serialized in the end.
Advertisement
Categories: .net
The implicit 0 default, although it broadly matches the wire format, is slightly confusing. In hindsight, I should perhaps only looked at [DefaultValue].
In “v2″ (not yet released) this is more flexible, but I didn’t want to suddenly change it in v1 (a potentially breaking change).