1

I have a method that takes:

public delegate void SubscriberAction(string a, string b = null);

My method

public void Subscribe(SubscriberAction action)
{
    var consumer = new EventingBasicConsumer(Channel);
    consumer.Received += (model, eventArgs) =>
    {
        try
        {
            var body = eventArgs.Body;
            action?.Invoke(Encoding.UTF8.GetString(body), eventArgs.RoutingKey); 
            // The above works when I call it with one or two strings
        }
        finally
        {
            Channel.BasicAck(eventArgs.DeliveryTag, false);
        }
    };
    Channel.BasicConsume(Configuration.QueueName, false, consumer);
}

When I invoke this action as shown above it does recognize the optional parameter and I can call it as intended. However, the Subscribe method that takes this delegate parameter won't let me call it how I want.

So this won't work:

subscriber.Subscribe(x =>
{
    // do stuff
});

Only works when I do this

subscriber.Subscribe((x, y) =>
{
    // do stuff
});

Initially I was using Action<string> action as the parameter for Subscribe but needed to add an optional second string parameter and since Action does not allow optional parameters (correct me if I'm wrong), I found an answer saying to use a custom delegate as I have done above.

How can I call the Subscribe method with either one or both parameters?

Usman Khan
  • 676
  • 1
  • 7
  • 20
  • 1
    Seems this is a [duplicate](https://stackoverflow.com/q/5636218/3791245). Short answer is that invoking delegates requires all parameters; the compiler 'cheats' and inserts the extra params for you in 'normal' cases. But when _defining_ a delegate (e.g. creating a lambda function), all parameters are needed. – Sean Skelly Nov 17 '20 at 18:37

1 Answers1

0

Return to Action<String, String> and add anothet Subscribe method:

public void Subscribe(Action<string> action) => Subscribe((x, y) => action(x));
Quercus
  • 2,015
  • 1
  • 12
  • 18
  • 1
    Well, as Sean Kelly mentioned in his comment you can't create delegate without argument even if it is optional, but in your `Subscriber` class you can have two `Subscribe` methods - one for two argument function, and another (which I wrote) for single-argument function, and this second version simply wraps single-argument function into double-argument and gives it to usual `Subscribe`. So, all subscription logic is only in initial function, and you can use both 1 and 2 argument functions as subscriptions – Quercus Nov 17 '20 at 18:59