C# Enum Flags

675 views
Skip to first unread message

Teddy Zhang

unread,
Nov 23, 2015, 7:52:53 PM11/23/15
to Protocol Buffers
C# supports Enum Flags, which is a nice feature.

   [Flags]
   enum MyColor
   {
      None = 0,
      Black = 1,
      Red = 2,
      Green = 4,
      Blue = 8
   };

However, protobuf seems doesn't support it. There is no way to define a Flags for an enum.
Also, for protobuf2, it seem current implementation is forbidden values that are combinations (e.g. 3). In that case it will treat it like unknown fields.
In current protobuf 3 c# implemention, the restriction seems gets removed. However, there is still no way to define the enum as Flags.

In Java we also have EnumSet to give similar functionality.

Will Protobuf C# implementation support this in the future?

Jon Skeet

unread,
Nov 24, 2015, 8:10:30 AM11/24/15
to Protocol Buffers
I wasn't anticipating doing so, no. Aside from anything else, it would be different from all the other platforms - you'd only end up with a useful enum in C# if the developer creating the proto did exactly the right thing... and that would look odd for other developers.

I would suggest just using a HashSet<YourEnumType> instead for a set - just like there's EnumSet in Java which is a set of values.

(I'm not sure what you mean by "current implementation is forbidden values that are combinations" - you can certainly define enums with values of 1, 2, 3, 4, 5 etc in proto2).

Jon

Teddy Zhang

unread,
Nov 24, 2015, 2:36:11 PM11/24/15
to Protocol Buffers
How do I store a HashSet<EnumType> with protobuf?

Regarding the proto2 implementation, if I defined my enum as 1, 2, 4 etc, and I set the enum to value 3 (combination of 1 & 2), it serialize the fields correctly. But when deserialize, I get value 0 back (as 3 is not in enum).

Jon Skeet

unread,
Nov 25, 2015, 7:51:37 AM11/25/15
to Protocol Buffers
On Tuesday, 24 November 2015 19:36:11 UTC, Teddy Zhang wrote:
How do I store a HashSet<EnumType> with protobuf?

Have a repeated field of the enum type, so that you get a collection - and then make sure you transform it into a set in your code. proto doesn't have the notion of a set as such.
 
Regarding the proto2 implementation, if I defined my enum as 1, 2, 4 etc, and I set the enum to value 3 (combination of 1 & 2), it serialize the fields correctly. But when deserialize, I get value 0 back (as 3 is not in enum).

Yes, because that's the defined behaviour in proto2 for an undefined value. You're trying to use proto enums in a way that they weren't designed for, which is never going to be a pleasant experience. It's not about being a "combination" of values - proto doesn't have any such concept. It's just a value which isn't defined.

Jon

Reply all
Reply to author
Forward
0 new messages