21

I have a list of method that I would like to call in a specific order. Therefore I would want to store them either in an ordered list or in a table with a specified index. This way the list would be the only thing to change the day we want to change the call order.

I found this article explaining how to do it using an array and delegates. But I read in the comments and some other places that it could also be done using a Dictionary and or LinQ. Any advices ?

5 Answers 5

40

You can define Action objects, which are parameterless delegates that return void. Each action is a pointer to a method.

// Declare the list
List<Action> actions = new List<Action>();

// Add two delegates to the list that point to 'SomeMethod' and 'SomeMethod2'
actions.Add( ()=> SomeClass.SomeMethod(param1) );
actions.Add( ()=> OtherClass.SomeMethod2() );

// Later on, you can walk through these pointers
foreach(var action in actions)
    // And execute the method
    action.Invoke();
3
  • 16
    You can omit Invoke() btw, just call action()
    – testalino
    Sep 22, 2010 at 9:37
  • 2
    Everything is ok but Queue is much more suitable for the OP's task rather than List, imo. Isn't it? Sep 22, 2010 at 9:49
  • 4
    Don't think so. It's just a static list, no need for queue'ing or dequeue'ing tasks, as they won't change dynamically. He might want to re-run the batch a couple of times etc. Sep 22, 2010 at 10:12
9

How about a Queue<Action> ?

var queue = new Queue<Action>();

queue.Enqueue(() => foo());
queue.Enqueue(() => bar());

while(queue.Count != 0)
{
    Action action = queue.Dequeue();
    action();
}
4

Why don't you consider using a Queue it's FIFO , store delegates in Queue and when you call Dequeue it will call your methods in a specified manner.

What about using Multicast Delegate , it stores delegates in a LinkList, so when you call Invoke() , it will be called in a specified manner.

0

I would advise to look at Command pattern. Hope it 's what you lookng for.

0

You could use List<> which would fit your need pretty well:

delegate void MyFunction(...);
List<MyFunction> delegateList;

If your delegate returns void, you can use event. Multiple delegates can be added to a single event invocation list and will be called in the order they were added.

delegate void MyEvent(...);
event MyEventEventHandler MyEvent;

Dictionary order is undefined and it's meant to make a lookup.

Your Answer

Reminder: Answers generated by Artificial Intelligence tools are not allowed on Stack Overflow. Learn more

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.