tags:

views:

86

answers:

4

I've got a loop that will need to "mark" functions to run later, after the loop is completed. Is that possible to do?

Thanks, Tyler

+6  A: 

You can store the function in a delegate:

private void Test(object bar)
{
    // Using lambda expression that captures parameters
    Action forLater = () => foo(bar);
    // Using method group directly
    Action<object> forLaterToo = foo;
    // later
    forLater();
    forLaterToo(bar);
}

private void foo(object bar)
{
    //...
}
Quartermeister
This was exactly what I needed! Plus I just learned about something brand new... Lambda Expressions *goes to investigate*
Tyler Murry
+2  A: 

Sure can, I recently wrote a program for my job that does that and more. Implement a command pattern. Conceptually its like a programmable remote control. It also allows for transactions and other neat little features.

P.Brian.Mackey
+1  A: 

Look at implementing events. This is exactly what they are for.

// define a delegate signature for your functions to implement:
public delegate void PostProcessingHandler(object sender, object anythingElse /*, etc.*/);

public class YourClass {

  // define an event that will fire all attached functions:
  public event PostProcessingHandler PostProcess;

  public void YourMethod() {

    while(someConditionIsTrue) {

      // do whatever you need, figure out which function to mark:
      switch(someValue) {
        case "abc": PostProcess += new PostProcessingHandler(HandlerForABC); break;
        case "xyz": PostProcess += new PostProcessingHandler(HandlerForXYZ); break;
        case "123": PostProcess += new PostProcessingHandler(HandlerFor123); break;
        default: break;
      } 
    }

    // invoke the event:
    if(PostProcess != null) { PostProcess(); }
  }

  public void HandlerForABC(object sender, object anythingElse) {  /*...*/  }

  public void HandlerForXYZ(object sender, object anythingElse) {  /*...*/  } 

  public void HandlerFor123(object sender, object anythingElse) {  /*...*/  }
}
Jeff Meatball Yang
+1  A: 
 Dictionary<Action, bool> functionsToRun = new Dictionary<Action, bool>();

 functionsToRun.Add(() => { Console.WriteLine("This will not run"); }, false);
 functionsToRun.Add(() => { Console.WriteLine("Run forest run!!!!!!"); }, true);

 foreach (KeyValuePair<Action, bool> function in functionsToRun)
 {
     if (function.Value)
         function.Key.Invoke();
 }

Hope that's what your looking for!

Ryan