Christian
Christian

Reputation: 4375

C# Method that executes a given Method

I am trying to write the following: I would like to write a method "A" which takes as parameter another method "B" as well as an unknown number of parameters for this method B. (params object[] args). Now, inside method A i would like to make a call to B with the parameters args. B will now return an object which I would like A to return as well.

This all sounds a bit strange, therefore I will add some example code:

public object A(Func<object> B, params object[] args)
{
    object x = B.Method.Invoke(args);

    return x;
}

The problem is, that Func does not work like that. Does anyone know a way of doing this?

Regards, Christian

Upvotes: 5

Views: 322

Answers (4)

spender
spender

Reputation: 120450

void Main()
{
    Func<int> m1=()=>1;
    Console.WriteLine(A(m1));

    Func<int,int> m2=i=>i;
    Console.WriteLine(A(m2,55));
}

object A(Delegate B,params object[] args)
{

    return B.Method.Invoke(B.Target,args);
}

...goodbye type-safety

Upvotes: 3

Mat&#237;as Fidemraizer
Mat&#237;as Fidemraizer

Reputation: 64923

You should have a code like this one:

public object A(Func<object[], object> B, params object[] args)
{
    object x = B(args);

    return x;
}

You're missing that the Func overload needs to accept your object array of arguments.

Anyway, if you need this method "A" to accept parameterless functions, you should create a paremeterless function parameter overload of "A".

Upvotes: 1

Fredrik M&#246;rk
Fredrik M&#246;rk

Reputation: 158309

Func<object> is a delegate for a method that takes no arguments and returns object. If you change it to Func<object,object>, it will take an argument and return object:

public object A(Func<object, object> B, params object[] args)
{
    object x = B(args);

    return x;
}

Upvotes: 3

Klaus Byskov Pedersen
Klaus Byskov Pedersen

Reputation: 120937

This should do it:

public object A(Func<object[], object> B, params object[] args) 
{     
     object x = B(args);     
     return x; 
}

Upvotes: 1

Related Questions