NunezGui / protobuf-net

Automatically exported from code.google.com/p/protobuf-net
Other
0 stars 0 forks source link

Optional bool member with DefaultValue(true) #366

Open GoogleCodeExporter opened 8 years ago

GoogleCodeExporter commented 8 years ago
NUnit test reproducing problem:

    [ProtoContract]
    public class TestProto
    {
        [ProtoMember(1, IsRequired = false), DefaultValue(true)]
        public bool Bug { get; set; }
    }

    [TestFixture]
    public class ProtobufTests
    {
        [Test]
        public void TestProto()
        {
            var protoObj = new TestProto {Bug = true};
            var ms = new MemoryStream();
            Serializer.Serialize(ms, protoObj);
            var protoBytes = ms.ToArray();
            var deserializedObj = Serializer.Deserialize<TestProto>(new MemoryStream(protoBytes));
            Assert.IsTrue(deserializedObj.Bug);
        }
    }

What is the expected output? Boolean property is true.

What do you see instead? It is false instead.

I'm using protobuf-net 2.0.0.621 (last version from nuget) on Windows 7 64, 
.Net 4 (and 4.5).

Original issue reported on code.google.com by asvya...@gmail.com on 6 Apr 2013 at 4:39

GoogleCodeExporter commented 8 years ago
DefaultValueAttribute, as used by multiple parts of the system (not just 
protobuf-net) expects **your code** to assign the default. For example in the 
constructor or field initializer. The code you show would fail in multiple .NET 
usages.

Easy option: assign the property to true in the constructor.

Original comment by marc.gravell on 6 Apr 2013 at 6:48