3

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?

5 Answers 5

5

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
}
1
  • All answers to my question were sufficient, but your answer helped delegates click for me, so I accepted yours. Thanks, everyone.
    – frenchgoat
    Feb 11, 2010 at 5:13
4

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);      
   }
}
2

You can pass an parameterized method that returns void using an Action delegate. You could then do something like this:


public void Main()
{
    MethodQueue(MethodOne);
} 
public void MethodOne(int x, int y) 
{
    // do stuff
}
public void MethodQueue(Action<int, int> method)
{
    // wait
    method(0, 0);
}
You can also use a Func delegate if your method needs to return a value.

2

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();
    }


 }
0

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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.