4

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?

chwarr
  • 6,777
  • 1
  • 30
  • 57
  • You probably want `repeated` instead of `repeater`. – Yash Tibrewal Sep 16 '20 at 17:39
  • Does this answer your question? [Property or indexer of type RepeatedField cannot be assigned to — it is read only](https://stackoverflow.com/questions/47556250/property-or-indexer-googleprotobuf-repeatedfield-cannot-be-assigned-to-it-is-r) – chwarr Sep 19 '20 at 01:51

2 Answers2

8

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);
Pretenddead
  • 81
  • 1
  • 2
5

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.

Edamreed
  • 271
  • 3
  • 10
  • [This gives you a good idea why your solution works](https://stackoverflow.com/a/52314241/6369752). If I could paraphrase, collection initializers (i.e. the assignment with braces) will work on any object that implements `IEnumerable` and has the `.Add()` method. From what I can tell, this is syntactic sugar for calling the `.Add()` method with a read only field. – Sal Alturaigi Mar 24 '22 at 09:19