1
votes

Using the latest protobuf-net for proto2 .proto files I tried on Marc's site's generator:

syntax = "proto2";

message my_message {
  optional string val1 = 1 [default="hello!"];
  required uint32 val2 = 2 [default="4"];
}

For the optional field val1 it correctly adds the code for the default value, however it's not generated for the required val2. What I was expecting it that it would generate the same code and I wouldn't have to explicitly set the val2 field since it was already set by the default value. Why is this not the case?

1

1 Answers

1
votes

This is a common source of confusion. Default values don't do what you're expecting them to do.

A default value says, exactly: "If the setter for this field has not been called (or the message was parsed from the wire, and this field wasn't present there), then getter for this field should return this value."

Default values are entirely local. They are never sent over the wire.

This means that setting a default value for a required field is mostly useless. The only thing it does is determine what the field's getter method will return when the object is first created.

Also note that the purpose of a required field is to force the sender of a message to call the field's setter before sending. If you don't want to require the sender to set the field explicitly, then you should declare the field optional. (Actually, you should always declare fields optional, never required, but that's another story.)

(Disclosure: I'm the author of proto2-c++, protoc, and Cap'n Proto, but not proto3.)