How can I use protobuf's Any in C#?

Viewed 3466

Here is my protobuf's data model:

message GetNewsRespone{
  repeated google.protobuf.Any instrument = 1;
}

message Issue{
  int64 id = 1;
  string title = 2;
}

And here is my attempt to fill that with data:

GetNewsRespone res = new GetNewsRespone();
Issue issue = new Issue();
issue.id = 123;
layer.instrument .AddRange(???);

How can I add anIssue to my GetNewsRespone.instrument, which is an Any Array?

2 Answers

Use Google.Protobuf.WellKnownTypes.Any.Pack

like:

var myValue = Google.Protobuf.WellKnownTypes.Any.Pack(new Stock());

for your code:

GetNewsRespone res = new GetNewsRespone();
Issue issue = new Issue();
issue.id = 123;
res.instrument = Google.Protobuf.WellKnownTypes.Any.Pack(issue);

You have methods you can use in the C#, provided by the Any class. Let me give you an example.

Let's say we have the following protocol buffer:

syntax "proto3"

import "google/protobuf/any.proto"

message Stock {
    // Stock-specific data
}

message Currency {
    // Currency-specific data
}

message ChangeNotification {
    int32 id = 1;
    google.protobuf.Any instrument = 2;
}

And in the C# code.the Any class provides methods for setting the field, extracting the message, and checking the type.

public void FormatChangeNotification(ChangeNotification change)
{
    if (change.Instrument.Is(Stock.Descriptor))
    {
        FormatStock(change.Instrument.Unpack<Stock>());
    }
    else if (change.Instrument.Is(Currency.Descriptor))
    {
        FormatCurrency(change.Instrument.Unpack<Currency>());
    }
    else
    {
        throw new ArgumentException("Unknown instrument type");
    }
}

Hope I helped you understand how you can implement it on your own code.

Related