How to determine at runtime the name of the oneof field that is set?

Viewed 162

Using protobuf-net, instead of iterating through each ShouldSerialize*(), how do I determine which oneof is set? I see that ShouldSerialize*() uses this internally __pbn__message.Is(7) but that private property is not accessible, and I also don't know how to get the max field number?

Trying to avoid iterating through each ShouldSerialize*() method because then when a new type is added, we'd need to update the iteration too.

Similar question but solved using Google's Nuget package instead: Getting all field names from a protocol buffer?

1 Answers

Assuming you're using the schema parsing tools: there is an option to emit an enum and accessor that tells you exactly this. Just enable this option, and: done. How exactly to access this option depends on how you're running the tooling (at the command-line, the build-time generator, via the website, etc).

If you're writing it manually: check the .Discriminator accessor on the discriminated union field. To copy and paste from an answer yesterday: all the option adds is the equivalent of the following (but for your context):

public ContentOneofCase ContentCase => (ContentOneofCase)__pbn__Content.Discriminator;

public enum ContentOneofCase
{
    None = 0,
    Foo = 1,
    Bar = 2,
    Blap = 3,
}
Related