Is it possible to store a lambda expression in a C # array

I am writing an AI game engine, and I would like to store some lambda expressions / delegates (several argument lists) in an array.

Something like that:

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

Is this possible in C #?

+7
c # lambda
source share
2 answers

Instead of List<Action> you can create

 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 a single item:

 _events[0](); 
+7
source share

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(); 
+5
source share

All Articles