Thomas
Thomas

Reputation: 2984

C# methods with variable paramterlist as parameter

Hi I'm currently trying to pass methods (with no return value) as parameters to another method (so that they can be called from within the methods).

The problem I'm currently having is, that I'm using Action in the parameterlist and thus need to exactly define which parameters this method takes.

The question thus is: Is there any way to omit this? Thus that I don't have to define which parameters exactly the method has in the parameterdeclaration?

Codeexample:

public void A(int myint)
{
   Console.WriteLine(myint.ToString());
}

public void B(int myint1, int myint2)
{
   Console.WriteLine((myint1 + myint2).ToString());
}


public void myQuestionMethod(Action<int> parameterMethod)
{
    //....Dosomething special by creating the parameters within and calling the given methods
}


myQuestionMethod(A);
myQuestionMethod(B);

Thus Aciton parameterMethod can that be replaced by something else that allows me to give methods as parameters who have differing parameters?

Edit: I forgot to mention that the TYPE of the parameters is also not fixated.

Thus a function C could exist with (int param1, String param2)

Upvotes: 0

Views: 88

Answers (3)

ken2k
ken2k

Reputation: 48975

One solution would be to use reflection. Of course don't use it unless you do not have any other choice (specifying a method using its name should be avoided if possible):

public class Foo
{
    public void A(int myint)
    {
        Console.WriteLine(myint.ToString());
    }

    public void B(int myint1, int myint2)
    {
        Console.WriteLine((myint1 + myint2).ToString());
    }

    public void myQuestionMethod(string parameterMethodName, params object[] parameters)
    {
        var method = this.GetType().GetMethod(parameterMethodName, BindingFlags.Instance | BindingFlags.Public);
        method.Invoke(this, parameters);
    }
}

public class Test
{
    public static void Main()
    {
        var foo = new Foo();

        foo.myQuestionMethod("B", 1, 2);

        Console.Read();
    }
}

Upvotes: 0

James
James

Reputation: 82096

Depending on how big your methods are, you could go for just Action and use anonymous methods rather than explicitly defining the functions

public void myQuestionMethod(Action parameterMethod)
{
    //
}
...
myQuestionMethod(() => Console.WriteLine(myInt.ToString()));
myQuestionMethod(() => Console.WriteLine((myInt1 + myInt2).ToString()));

Upvotes: 0

Patrick Hofman
Patrick Hofman

Reputation: 156938

No. There is no way to do this with the Action delegate (that's why there are 16 overloads).

You could opt, if the variables are all of the same type and have the same meaning, to create an array of integers:

public void A(params int[] myint)
{
}

public void myQuestionMethod(Action<int[]> parameterMethod)
{
    //....Dosomething special by creating the parameters within and calling the given methods
}

Upvotes: 3

Related Questions