Question

I'm writing a game AI engine and I'd like to store some lambda expressions/delegates (multiple lists of arguments) in an array.

Something like that:

 _events.Add( (delegate() { Debug.Log("OHAI!"); }) );
 _events.Add( (delegate() { DoSomethingFancy(this, 2, "dsad"); }) );

Is it possible in C#?

Was it helpful?

Solution

You can make a List<Action> instead:

List<Action> _events = new List<Action>();
_events.Add( () => Debug.Log("OHAI!")); //for only a single statement
_events.Add( () =>
    {
        DoSomethingFancy(this, 2, "dsad");
        //other statements
    });

Then call an individual item:

_events[0]();

OTHER TIPS

you can use System.Action.

var myactions = new List<Action>();
myactions .Add(new Action(() => { Console.WriteLine("Action 1"); }) 
myactions .Add(new Action(() => { Console.WriteLine("Action 2"); }) 

foreach (var action in myactions)
  action();
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top