0

I wish to create an extension method that takes A function with a parameter of IEnumerable<T>.

int NumberOfRetries = 3;
string TableName = "Table";

Method(EnumerableParameter).RetrySection(EnumerableParameter,TableName ,NumberOfRetries);

Function to be extended

bool Method(IEnumerable<int> param)
{
  foreach(var item in param)
  {
    Console.WriteLine(item);
  }
  return true;
}

I am having difficulty making the code compile

RetrySection(() => Method(EnumerableParameter),EnumerableParameter,TableName ,NumberOfRetries);

for both options.

Method(EnumerableParameter).RetrySection(EnumerableParameter,TableName,NumberOfRetries);

Extension Method

public static void RetrySection(this Func<IEnumerable<T>,bool> action, IEnumerable<T> parameter,string databaseTable,int jobcount)
        {
            int jobRowCount = ValidateTable(databaseTable).GetAwaiter().GetResult();
            int retry = 0;

            do
            {
                action(parameter);

                jobRowCount = ValidateTable(databaseTable).GetAwaiter().GetResult();
                retry++;
            }
            while ((jobRowCount < (jobcount * 2)) && retry < 3);
        }

I'm getting the error Func<IEnumerable<int>,bool> does not take 0 arguments.

agent_bean
  • 1,493
  • 1
  • 16
  • 30
  • Try adding braces to the first one, like `() => { return Method(EnumerableParameter); }` – Emanuel Vintilă Nov 11 '20 at 21:09
  • You have to use a valid _delegate_ instance when calling that extension method. You can't extend the original method call itself. You need to pass a delegate created from the method, which precludes use of the method-group-to-delegate inference feature of the language. You could do `((Func, bool>)Method).RetrySection(EnumerableParameter, ...)` or `RetrySection(Method, EnumerableParameter, ...)`. Though frankly, I find either missing the point of a generalized retry implementation. See duplicate for how you _ought_ to be doing this. – Peter Duniho Nov 11 '20 at 21:28

1 Answers1

0

The solution is to use:

Method.RetrySection(EnumerableParameter,TableName ,NumberOfRetries);

because that is what RetrySection is defined to work on - Func<IEnumerable,bool>, instead of the result - bool.

Or, in case of the second example:

RetrySection(Method,EnumerableParameter,TableName ,NumberOfRetries);
Jakub Fojtik
  • 681
  • 5
  • 22
  • how does action get invoked. in the do while loop if i'm extending a boolean? – agent_bean Nov 11 '20 at 21:17
  • You are not extending a booelan, you are extending a function that takes an IEnumerable and returns a boolean: `void RetrySection(this Func,bool> action` – Jakub Fojtik Nov 11 '20 at 21:19
  • I don't think the first option compiles as `Method.RetrySection`. You should have to cast the method as `((Func, bool>)Method).RetrySection` – devNull Nov 11 '20 at 21:27
  • You are right @devNull, it is required: https://dotnetfiddle.net/Widget/TqyVJX – Jakub Fojtik Nov 11 '20 at 21:34