frenchgoat
frenchgoat

Reputation: 430

quick-and-dirty way to pass a method with parameters, as a parameter?

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?

Upvotes: 3

Views: 309

Answers (5)

Steve
Steve

Reputation: 12004

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


 }

Upvotes: 2

revenantphoenix
revenantphoenix

Reputation: 316

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

Upvotes: 0

Martin Booth
Martin Booth

Reputation: 8595

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
}

Upvotes: 5

Shane Fulmer
Shane Fulmer

Reputation: 7708

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.

Upvotes: 2

Preet Sangha
Preet Sangha

Reputation: 65476

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

Upvotes: 4

Related Questions