Question

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

Was it helpful?

Solution

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

OTHER TIPS

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

This should do it:

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

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".

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top