protobuf-csharp-port icon indicating copy to clipboard operation
protobuf-csharp-port copied to clipboard

Problem with required enum field with default value

Open TeunVR opened this issue 10 years ago • 3 comments
trafficstars

Consider the following .proto file:

message TestMessage {
    enum Result {
        OK = 0;
        FAILED = 1;
        TIMEOUT = 2;
    }
    required Result result = 1 [default = OK];
}

I would expect to be able to build a new TestMessage with:

TestMessage msg = TestMessage.CreateBuilder().Build();

This fails with: An unhandled exception of type 'Google.ProtocolBuffers.UninitializedMessageException' occurred in Google.ProtocolBuffers.dll Additional information: Message missing required fields: result

If i look at the generated code, the result-field is correctly set. However, the hasResult boolean is not set to true.

  public const int ResultFieldNumber = 1;
  private bool hasResult;
  private global::TestMessage.Types.Result result_ = global::TestMessage.Types.Result.OK;
  public bool HasResult {
    get { return hasResult; }
  }
  public global::TestMessage.Types.Result Result {
    get { return result_; }
  }

  public override bool IsInitialized {
    get {
      if (!hasResult) return false;
      return true;
    }
  }

I would expect the result field to have a default value, so i think hasResult should be initialized to true if a default value is set.

Note: using version 2.4.1.555

Or should this issue be submitted in https://github.com/google/protobuf ?

TeunVR avatar Jul 22 '15 10:07 TeunVR

Or should this issue be submitted in https://github.com/google/protobuf ?

No, absolutely not - the code there is very different now (at least on the csharp-experimental branch, which I hope to merge soon).

Your expectation here looks reasonable, but I don't expect to have the time to work on this any time soon (and this codebase is effectively legacy code at this point).

The simpler solution is just to make it an optional field - a required field with a default feels like a bit of a contradiction in terms. I realize this doesn't help if don't control the proto definition.

jskeet avatar Jul 22 '15 10:07 jskeet

Thanks. While i think a required field with a default value should work (for example: there must be a result-field and i don't have to set it if the result is OK) , i can workaround it by using an optional field as you suggested.

By the way: is the official csharp implementation in https://github.com/google/protobuf only going to be proto3?

TeunVR avatar Jul 22 '15 10:07 TeunVR

By the way: is the official csharp implementation in https://github.com/google/protobuf only going to be proto3?

That's my current plan, yes. It allows us to remove an awful lot of complexity.

jskeet avatar Jul 22 '15 10:07 jskeet