Ralph Jason Caballes
Ralph Jason Caballes

Reputation: 151

How to add value to a ProtoBuf repeated field in C#

I am new to Grpc and I wish to make a list of value for a request and in order to do that I need a repeater. The code is shown below.

syntax = "proto3";

option csharp_namespace = "Test.Grpc.Server.Protos";

package test;

service VcaAdministrator {
    rpc ForceStop (ForceStopRequest) returns (ForceStopResponse);
}

message ForceStopRequest{
    repeated string Id = 1;
}

message ForceStopResponse{
    bool stopped = 1;
}

I wish to pass value to the ForceStopRequest.

        var cmd = new Command("ForceStop");
        cmd.AddOption(new Option<string>("--id", getDefaultValue: () => "null", description:"Force stop"));

        cmd.Handler = CommandHandler.Create(async (List<string> id) =>
        {
            var request = new ForceStopVcaRequest()
            {
                Id = id
            };

            var response = await vcaAdministratorClient.ForceStopVcaAsync(request);
            Console.WriteLine($"{response.Stopped} {response.ErrorCode} {response.ErrorMessage}");
        });

        return cmd;

But the code above generate an error "Property or indexer 'ForceStopRequest.Id' cannot be assigned to -- it is read only." How to fix this issue?

Upvotes: 8

Views: 22128

Answers (2)

Edamreed
Edamreed

Reputation: 381

Not sure if this is just a VS version thing or not but

GetCompaniesReply result = new() { 
                Companies = theList
}

Does not work but

GetCompaniesReply result = new() { 
                Companies = {theList}
}

Does

Wrapping the object in those extra {} works for me.

Upvotes: 16

Pretenddead
Pretenddead

Reputation: 101

Any properties of a repeating field are read-only. You can add items to or remove items from a collection, but you cannot replace it with a completely separate collection.

So, you can try it for that :


var request = new ForceStopVcaRequest();
request.Id.Add(id);

Upvotes: 10

Related Questions