views:

106

answers:

5

Let me just preface this with the fact that I'm pretty green to C#. That being said, I'm looking for a way to pass a method with a parameters as a parameter. Ideally, what I want to do is:

static void Main(string[] args)
{
    methodQueue ( methodOne( x, y ));
}

static void methodOne (var x, var y)
{
    //...do stuff
}

static void methodQueue (method parameter)
{
    //...wait
    //...execute the parameter statement
}

Can anyone point me in the right direction?

+2  A: 
Shane Fulmer
+3  A: 

Use an Action delegate

// Using Action<T>

using System;
using System.Windows.Forms;

public class TestAction1
{
   public static void Main()
   {
      Action<string> messageTarget; 

      if (Environment.GetCommandLineArgs().Length > 1)
         messageTarget = ShowWindowsMessage;
      else
         messageTarget = Console.WriteLine;

      messageTarget("Hello, World!");   
   }      

   private static void ShowWindowsMessage(string message)
   {
      MessageBox.Show(message);      
   }
}
Preet Sangha
+4  A: 

This should do what you want. It is actually passing in a parameterless medthod to your function, but delegate(){methodOne( 1, 2 );} is creating an anonymous function which calls methodOne with the appropriate parameters.

I wanted to test this before typing it but only have .net framework 2.0 hence my approach.

public delegate void QueuedMethod();

static void Main(string[] args)
{
    methodQueue(delegate(){methodOne( 1, 2 );});
    methodQueue(delegate(){methodTwo( 3, 4 );});
}

static void methodOne (int x, int y)
{

}

static void methodQueue (QueuedMethod parameter)
{
    parameter(); //run the method
    //...wait
    //...execute the parameter statement
}
Martin Booth
All answers to my question were sufficient, but your answer helped delegates click for me, so I accepted yours.Thanks, everyone.
haunt1983
A: 

You could also use the pure C alternative of function pointers, but that can get a little bit messy, though it works splendidly.

revenantphoenix
+2  A: 

Using lambda syntax, which is almost always the most concise way. Note that this is functionally equivalent to the anonymous delegate syntax

 class Program
 {
    static void Main(string[] args)
    {
        MethodQueue(() => MethodOne(1, 2));
    }

    static void MethodOne(int x, int y)
    {...}

    static void MethodQueue(Action act)
    {
        act();
    }


 }
Steve