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

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.

Advertisements
Categories: .net
  1. May 21, 2010 at 1:32 pm

    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).

  1. No trackbacks yet.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: