1
votes

The default values for classes generated with protogen don't seem to be serialized when UseImplicitZeroDefaults = false.

I have a small .proto file:

package protobuf;

option java_package = "com.company.protobuf";
option java_outer_classname = "Test";

message TestMessage{        
    optional string Message = 1;
    optional bool ABool = 2;
    optional int32 AnInt = 3;           
}

Using protogen.exe, I've generated a TestMessage class that I'm trying to send back and forth across the wire to a Java app. I can't seem to get protobuf-net to serialize a value of zero for AnInt or false for ABool, including setting UseImplicitZeroDefaults=false. However, using annotated classes for serialization with that setting works. Here's an equivalent class to the one I generated:

[ProtoContract]
class Test2
{
    [ProtoMember(1)]
    public string Message { get; set; }
    [ProtoMember(2)]
    public bool ABool { get; set; }
    [ProtoMember(3)]
    public int AnInt { get; set; }
}

Initializing the two classes with the same data and serializing to byte[] shows that four extra bytes are coming from the annotated class.

...
private static readonly RuntimeTypeModel serializer;
static Program()
{
    serializer = TypeModel.Create();
    serializer.UseImplicitZeroDefaults = false;
    Console.WriteLine(serializer.UseImplicitZeroDefaults); //prints false 
}

static void SendMessages(ITopic topic, ISession session)
{
    Console.WriteLine(serializer.UseImplicitZeroDefaults);

    TestMessage t = new TestMessage();
    t.ABool = false;
    t.AnInt = 0;
    t.Message = "Test Message";

    using (var o = new MemoryStream())
    {
        serializer.Serialize(o, t);
        Console.WriteLine(string.Format("Tx: Message={0} ABool={1} AnInt={2}", t.Message, t.ABool, t.AnInt));
        Console.WriteLine(o.ToArray().Length);
    }

    Test2 t2 = new Test2();
    t2.ABool = false;
    t2.AnInt = 0;
    t2.Message = "Test Message";
    using (var o = new MemoryStream())
    {
        serializer.Serialize(o, t2);
        Console.WriteLine(string.Format("Tx: Message={0} ABool={1} AnInt={2}", t.Message, t.ABool, t.AnInt));
        Console.WriteLine(o.ToArray().Length);
    }
}

Output:

False
Tx: Message=Test Message ABool=False AnInt=0
14
Tx: Message=Test Message ABool=False AnInt=0
18

Is there a setting I'm missing? Or do classes generated from .proto files use a different mechanism for serialization? In an ideal world, I would expect the UseImplicitZeroDefaults setting to get picked up by both the annotated and generated classes on their way through the serializer.

1

1 Answers

1
votes

If you add -p:detectMissing to your call to protogen, it should emit code following a different pattern that allows for better tracking of these. Basically, it should do what you want then.