user3789007
user3789007

Reputation: 23

Method running another method

Is it possible to run another method using run()?

public void a(int a)
{
    // Method1
}

public void b(int b)
{
    // Method2
}

//how to run code below
public void run(? b(23))  <--can be change to a or b 
{
    b(23);
}

Edit: What if I want to return a value from the methods?

public static int a(int a)
{
    // Method1
}

public static int b(int b)
{
    // Method2
}

//how to run code below
public static int run(? b(23))  <--can be change to a or b 
{
    b(23);
}

Upvotes: 0

Views: 47

Answers (3)

Grant Winney
Grant Winney

Reputation: 66449

There's a few ways you could do this. One way would be to define your run method like this:

public void run(Action action)
{
    action.Invoke();
}

Then execute one method or the other using:

run(() => a(3));

run(() => b(5));

If you want to return a value, you can either do so in two steps:

int r = 0;
run(() => r = b(3));

Or switch to a Func<>:

public T run<T>(Func<T> method)
{
    return method.Invoke();
}

And then call it likewise:

var r = run(() => b(3));

Upvotes: 3

cyberj0g
cyberj0g

Reputation: 3787

Are you talking about delegates? You can achieve what you want like that with Action delegate:

    private static void a(int arg)
    {
        Console.WriteLine("a called: " + arg);
    }

    private static void b(int arg)
    {
        Console.WriteLine("b called: "+arg);
    }

    public static void run(Action<int> action, int arg)
    {
        action(arg);
    }

    private static void Main(string[] args)
    {
        run(a, 1);
        run(b, 2);
        Console.ReadLine();
    }

Upvotes: 1

KennyXu
KennyXu

Reputation: 139

public void run(Action<int> b)
{
    b(23)
}
run(a);
run(b);

Upvotes: 0

Related Questions