Search code examples
c#protocol-buffersprotobuf-net

Protobuf-net deserialize string field to c# guid


In a simplified scenario, assume we have a custom c# type which contains a guid field and the corresponding proto type is,

message HelloReply {
  string message = 1;
  string guid_id = 2; // this is defined GUID in corresponding c# type
  repeated string names = 3;
  map<string, double> prices = 4;
}

When I try to deserialize this proto to c# type, I get exception stating 'Invalid wire-type' and a link to explanation which is not helpful to me. Is there a work around for this or am I overlooking something ?


Solution

  • Protobuf-net has opinions on guids. Opinions that were forged back in the depth of time, and that I now regret, but which are hard to revert without breaking people. If I was writing this today with hindsight, yes: it would probably just serialize as a string. But: that isn't what it expects today!

    Frankly I'd hack around it with a shadow property. So instead of

    [ProtoMember(42)]
    public Guid Foo {get;set;}
    

    You could use:

    public Guid Foo {get;set;}
    [ProtoMember(42)]
    private string FooSerialized {
        get => Foo.ToString(); // your choice of formatting
        set => Foo = Guid.Parse(value);
    }