Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Storing a list of methods in C#

Tags:

c#

.net

.net-3.5

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 ?

like image 908
Jla Avatar asked Sep 22 '10 09:09

Jla


3 Answers

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();
like image 147
Jan Jongboom Avatar answered Oct 28 '22 07:10

Jan Jongboom


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();
}
like image 25
abatishchev Avatar answered Oct 28 '22 05:10

abatishchev


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.

like image 4
TalentTuner Avatar answered Oct 28 '22 06:10

TalentTuner