InvalidOperationException when serializing [Flags] enum with protobuf-net

Viewed 467

I am trying to serialize an enum type that is decorated with [Flags] attribute. The enum declaration is as follows:

[Flags]
[ProtoContract(EnumPassthru = true)]
public enum Categories
{
    [ProtoEnum(Name = nameof(Invalid), Value = 0x0)]
    Invalid = 0x0,

    [ProtoEnum(Name = nameof(A), Value = 0x1)]
    A = 0x1,
    [ProtoEnum(Name = nameof(B), Value = 0x2)]
    B = 0x2,
    [ProtoEnum(Name = nameof(C), Value = 0x4)]
    C = 0x4,
    [ProtoEnum(Name = nameof(D), Value = 0x8)]
    D = 0x8,
    [ProtoEnum(Name = nameof(Global), Value = 0x1 | 0x2 | 0x4 | 0x8)]
    Global = A | B | C | D,
}

Now, when I try to serialize the container object, I get

InvalidOperationException:Operation is not valid due to the current state of the object.

Following other similar posts on SO, I have tried the following:

  1. Add EnumPassthru = true parameter in my enum's ProtoContract attribute
  2. Use RuntimeTypeModel.Default[typeof(Categories)].EnumPassthru = true; at the app startup phase,
  3. Provided the container object's enum-valued field with the IsRequired parameter [ProtoMember(6, IsRequired = true)]

Is there anything else that I miss with my enum declaration?

The beginning of the exception detail goes like:

InvalidOperationException:Operation is not valid due to the current state of the object.\r\n at ProtoBuf.Serializers.EnumSerializer.EnumToWire(Object value) in c:\Users\onur.gumus\Desktop\protobuf-net-master\protobuf-net\Serializers\EnumSerializer.cs:line 83\r\n at ProtoBuf.Serializers.EnumSerializer.Write(Object value, ProtoWriter dest) in c:\Users\onur.gumus\Desktop\protobuf-net-master\protobuf-net\Serializers\EnumSerializer.cs:line 125\r\n at ProtoBuf.Serializers.FieldDecorator.Write(Object value, ProtoWriter dest) in c:\Users\onur.gumus\Desktop\protobuf-net-master\protobuf-net\Serializers\FieldDecorator.cs:line 38\r\n at ProtoBuf.Serializers.TypeSerializer.Write(Object value, ProtoWriter dest) in c:\Users\onur.gumus\Desktop\protobuf-net-master\protobuf-net\Serializers\TypeSerializer.cs:line 173\r\n at ProtoBuf.Meta.TypeModel.TrySerializeAuxiliaryType(ProtoWriter writer, Type type, DataFormat format, Int32 tag, Object value, Boolean isInsideList) in c:\Users\onur.gumus\Desktop\protobuf-net-master\protobuf-net\Meta\TypeModel.cs:line 125 ...

1 Answers
Related