BladeMight
BladeMight

Reputation: 2810

Pass function 1 as argument to function 2 that will retrieve function 1 result as object

I have two functions, one receives function as parameter and tries to return the result of return of the passed function, second just function that returns object, which i cast later.

object function1(Action act) {
    object result = act();
    // do something with result
    return result;
}
object function2() {
    return (object)"string as object";
}

And it says that action does not have return type, I'd like to calling it this way:

function1(() => function2); // so it'll return "string as object" as object.

Upvotes: 0

Views: 64

Answers (1)

Claudio Redi
Claudio Redi

Reputation: 68400

You need to change Action by Func<object> since Action encapsulates a method but does not return a value.

Another thing to improve is that you might be able to convert function1 to generics so you don't have to deal with casting

T function1<T>(Func<T> act)
{
    T result = act();
    // do something with result
    return result;
}

string function2()
{
    return "string as object";
}

And then use it like this

string myString = function1(function2);

Upvotes: 4

Related Questions