Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Weird thing happen while deserializing boolean data member with inline initialization

when serializing a type that has a boolean member that is inline intialized to true - I always get the value as true on deserialization of the object (obviously, the problem is when the actual value of the member was false before the serialization). this does not happen in the opposite case (inline initialized to false and object value is true - I have also tried other manipulations and other data member types and they all work just fine).

here is the type:

[ProtoContract]
public class SomeObject
{
    public SomeObject() {}

    [ProtoMember(1)]
    private bool m_SomeMember = true;

    public bool SomeMember
    {
        get { return m_SomeMember; }
        set { m_SomeMember = value; }
    }
}

here is the code:

var stream = new MemoryStream();
var data = new SomeObject() {SomeMember = false};
Serializer.SerializeWithLengthPrefix<SomeObject>(stream, data , PrefixStyle.Base128);
stream.Position = 0;
var deserializedObject = Serializer.DeserializeWithLengthPrefix<SomeObject>(stream, PrefixStyle.Base128);

while looking at the values of the deserializied object - the SomeMember value is true. this doesn't make much sense, since the inline members initialization code should be inserted into the default ctor by the compiler - and as far as I understand protobuf should set values of members only after the ctor is being called (don't think it is possible otherwise) so, HELP? (Marc?)

like image 294
Moti Goldklang Avatar asked Nov 14 '22 00:11

Moti Goldklang


1 Answers

By default, protobuf-net uses implicit zero defaults (and false is considered a zero). You can tell it what you mean:

[ProtoMember(1), DefaultValue(true)]
private bool m_SomeMember = true;

or you can (via RuntimeTypeModel.UseImplicitZeroDefaults) disable this behaviour, so that only explicit defaults are processed.

like image 116
Marc Gravell Avatar answered May 12 '23 12:05

Marc Gravell