Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible to store lambda expression in array C#

Tags:

c#

.net

lambda

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#?

like image 519
neciu Avatar asked May 05 '14 16:05

neciu


2 Answers

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]();
like image 147
gunr2171 Avatar answered Oct 20 '22 21:10

gunr2171


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();
like image 28
milagvoniduak Avatar answered Oct 20 '22 20:10

milagvoniduak