views:

51

answers:

2

I am using protobuf-net in my application for serializaion/deserialization. I am facing an issue.

[ProtoContract()]
ClsTest
{
    private bool _isPeriodic

    [ProtoMember(1)]
    public bool IsPeriodic
    {
        get
        {
             return _isPeriodic;
        }

        set
        {
            isPeriodic = value;
        }
   }

}

I am using this class in my collction object.

The serialization process workes fine, but after deserialization the Value for property IsPeriodic by default is true eventhough it was false for some cases. Can anyone help me?

A: 

The following works fine for me:

[ProtoContract]
class ClsTest
{
    [ProtoMember(1)]
    public bool IsPeriodic { get; set; }
}

Deserialization:

   // stream is a NetworkStream object

   ClsTest clsTestObj = Serializer.DeserializeWithLengthPrefix<ClsTest>(stream, PrefixStyle.Fixed32);
   bool value = clsTestObj.IsPeriodic;
sonu
+1  A: 

My guess is that your code is setting IsPeriodic to true for default new instances, perhaps:

private bool _isPeriodic = true;

or, in the constructor you have:

_isPeriodic = true; // or IsPeriodic = true

Basically, there is an implicit default (following the protobuf language guide) where-by bool is assumed to have a default of false. It doesn't send data that is believed to be the default. If this default is incorrect, tell it:

[ProtoMember(1), DefaultValue(true)]

or IIRC you can try setting IsRequired to true instead:

[ProtoMember(1, IsRequired = true)]

and there are a few other ways of telling it to always send the value:

private bool ShouldSerializeIsPeriodic() { return true;}

(which uses the same pattern that is supported by core .NET for PropertyGrid, XmlSerializer, PropertyDescriptor, etc - it isn't me inventing random patterns)

Note that in "v2" I have made two further changes to help remove this oddity:

  • you can optionally bypass the constructor (WCF-style)
  • the new meta-model provides another way of deciding whether or not to assume a default
Marc Gravell
Thanks Marc,Now its working fine....:)thanks for providing protobuff-net .
Rakesh