Enums, C#, and Protocol Buffers

So, in the brave new world of microservice development, there’s this fancy technology called GRPC which allows you to define RPC-based microservices using Protocol Buffers as an IDL syntax and uses HTTP/2 as a transport underneath.

Now, Protocol Buffers’ IDL syntax supports enums. However, it doesn’t allow multiple enum values in different enums in the same namespace to have the same enum value, such as:

enum MyEnum {
FOO = 1;
BAR = 2;
}

enum OtherEnum {
FOO = 1;
BAR = 2;
}

What to do, what to do? The Protobuf compiler will complain, because FOO and BAR are the same name because that isn’t compatible with C++

The suggested alternative is to prefix your enum values with the name of the enum in ALL CAPS

enum MyEnum {
MYENUM_FOO = 1;
MYENUM_BAR = 2;
}

enum OtherEnum {
OTHERENUM_FOO = 1;
OTHERENUM_BAR = 2;
}

The cool thing is that the official C# compiler for Protobuf will convert this to idiomatic C# enums:

enum MyEnum {
Foo = 1;
Bar = 2;
}

enum OtherEnum {
Foo = 1;
Bar = 2;
}

Leave a Reply

Your email address will not be published. Required fields are marked *