Relativity
Relativity

Reputation: 6868

How to execute list of Action delegates with parameters

How to execute list of Action delegates with parameters

  public static void CompareAll(List<Action<object,object>> compareDelegates)
    {
        List<Exception> exceptions = new List<Exception>();

      // The issue is in below line - how to pass parameters to the delegate
        compareDelegates.ForEach(del = (a,b) =>
        {
            try
            {
                del.Invoke(a,b);
            }
            catch (Exception ex)
            {
                exceptions.Add(ex);
            }
        });
    }

and calling the above function from below code

List<Action<object, object>> compareDelegates = new List<Action<object, object>>();

        compareDelegates.Add((a,b) => Compare(1,2));
        CompareAll(compareDelegates);

Upvotes: 0

Views: 1322

Answers (2)

Amit
Amit

Reputation: 46323

Since your delegates don't do anything with the input they're passed, you should use an empty Action. Change your code to:

public static void CompareAll(List<Action> compareDelegates)
{
    List<Exception> exceptions = new List<Exception>();

    compareDelegates.ForEach(del =>
    {
        try
        {
            del.Invoke();
        }
        catch (Exception ex)
        {
            exceptions.Add(ex);
        }
    });
}

// somewhere else...
List<Action> compareDelegates = new List<Action>();

compareDelegates.Add(() => Compare(1,2));
CompareAll(compareDelegates);

EDIT: Since your question is puzzling, but doesn't really make sense in the way I solved above, here's another take

If you mean to have a list of Action<object,object> + 2 values, you should do that with a Tuple like this:

public static void CompareAll(
  List<Tuple<Action<Object,Object>,Object,Object>> compareDelegates)
{
    List<Exception> exceptions = new List<Exception>();

    compareDelegates.ForEach(tup =>
    {
        try
        {
            tup.Item1.Invoke(tup.Item2, tup.Item3);
        }
        catch (Exception ex)
        {
            exceptions.Add(ex);
        }
    });
}

// somewhere else...
List<Tuple<Action<Object,Object>,Object,Object>> compareDelegates = 
  new List<Tuple<Action<Object,Object>,Object,Object>>();

compareDelegates.Add(Tuple.Create((a,b) => Compare(a,b), 1, 2));
CompareAll(compareDelegates);

Upvotes: 1

31eee384
31eee384

Reputation: 2803

On this line:

compareDelegates.ForEach(del = (a,b) =>

Your parameter is very strange. The type signature for ForEach in this case is ForEach(Action<Action<object, object>>). Here's an example of how to use it.

object parameter1 = 2;
object parameter2 = 3;
compareDelegates.ForEach(a => a(parameter1, parameter2));

This calls every action in your list with 2 and 3. Your example isn't very clear what that really means, though.

Upvotes: 0

Related Questions