'Protobuf Message With Arbitrary Type (.NET)

I want to send/receive values with arbitrary types. At first, I thought the Any type would allow types such as string int32 etc. but it seems that the type must implement IMessage to pack or unpack it.

Is there a way to convert a string to an Any and vice versa?

If not, is there some other way to allow arbitrary types in messages?

E.g.

syntax = "proto3";

import "google/protobuf/any.proto";

package Engine;

message SomeMessage {
    string Id = 1;
    google.protobuf.Any AttributeValue = 2;
}

This code gives a compilation error in C#.

var someMessage = new SomeMessage
{
    Id = "123",
    AttributeValue = Any.Pack("Test")
};

Argument 1: cannot convert from 'string' to 'Google.Protobuf.IMessage'



Solution 1:[1]

It looks as though the answer may be the Value type.

syntax = "proto3";

import "google/protobuf/struct.proto";

package Engine;

message SomeMessage {
    string Id = 1;
    google.protobuf.Value AttributeValue = 2;
}

Solution 2:[2]

Packing a string in an Any type:

var someMessage = new SomeMessage
{
    Id = "123",
    AttributeValue = Any.Pack(new StringValue { Value = "foo bar"})
};

Unpacking the string:

var data = pack.Unpack<StringValue>();
doSomething(data.Value);

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1
Solution 2