Search code examples
c#.net-coregrpc

GRPC Optional Message doesn't generate field presence property


I am using optional to check for field presence.

e.g.

syntax = "proto3";

message ExampleClass{
    message ListFoo
    {
        repeated int64 foo = 1;
    }

    optional string name = 1;
    optional ListFoo foos = 2;
}

Then in the C# Code

The property HasName is generated, but HasFoos is not?

It seems they are expecting us to check for null. However in the case of a 'nullable list', I would still require field presence to determine if the intent was to set it to null.

So what is the best way to support a nullable list in grpc?


Solution

  • In proto3, optional has no meaning for a field where the type is a message. You can always tell whether or not a message field is set, even without optional.

    To check whether it's set in code, just use if (message.Foos is not null). There's no need for a HasFoos property. Likewise you don't need ClearFoos() - you just set message.Foos = null;. That is field presence.

    It seems they are expecting us to check for null. However in the case of a 'nullable list', I would still require field presence to determine if the intent was to set it to null.

    It's not clear what you mean by that, but there's no way of telling in protobuf whether a field has been explicitly cleared or whether it just hasn't been set. That's the same for all fields, including optional primitive fields. (There's no difference between a message which has had message.ClearName() called, and a message where Name was never populated.)

    To put it another way, a message contains state, not a change in state. So when a field supports presence, that means you can ask whether it's set or not, but you can't ask whether it's been cleared (as opposed to just never being set).