musium
musium

Reputation: 3072

C# protobuf-net - default value overwrites value from protobuf data

I need to serialize/deserialize classes using protobuf-net. For some properties of my classes, I need to define a default value. I did this by setting the values of the properties. In some cases this default value overwrites the value from the protobuf data.

Code Sample:

public class Program
{
    static void Main(string[] args)
    {
        var target = new MyClass
        {
            MyBoolean = false
        };

        using (var stream = new MemoryStream())
        {
            Serializer.Serialize(stream, target);
            stream.Position = 0;
            var actual = Serializer.Deserialize<MyClass>(stream);
            //actual.MyBoolean will be true
        }
    }
}

[ProtoContract(Name = "MyClass")]
public class MyClass
{
    #region Properties

    [ProtoMember(3, IsRequired = false, Name = "myBoolean", DataFormat = DataFormat.Default)]
    public Boolean MyBoolean { get; set; } = true;

    #endregion
}

MyBoolean will have a value of true after deserializing the data.

How can I fix this behavior?

Upvotes: 5

Views: 3589

Answers (1)

mklein
mklein

Reputation: 1807

For performance reasons default values are not serialized at all. The default of bool is false. Your default is true. To make this work you have to make your default value known with the DefaultValueAttribute:

    [ProtoMember( 3, IsRequired = false, Name = "myBoolean", DataFormat =  DataFormat.Default )]
    [DefaultValue(true)]
    public Boolean MyBoolean { get; set; } = true;

Upvotes: 9

Related Questions