Archive

Archive for May, 2010

protobuf-net: Beware of setting an optional int primitive to zero

May 21, 2010 1 comment

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.

Categories: .net