2

How can I define a function that expects another function that returns a bool in c#?

To clarify, this is what I'd like to do using C++:

void Execute(boost::function<int(void)> fctn)
{
    if(fctn() != 0)
    {
        show_error();
    }
}

int doSomething(int);
int doSomethingElse(int, string);

int main(int argc, char *argv[])
{
    Execute(boost::bind(&doSomething, 12));
    Execute(boost::bind(&doSomethingElse, 12, "Hello"));
}

In my example above the Execute function in combination is with the bind gets the expected result.

Background:

I've got a bunch of functions, each returning a int but with different parameter count that are surrounded by the same error checking code. A huge code duplication I want to avoid...

3 Answers 3

1

You can probably achieve what you want by using Func. For example

void Execute(Func<bool> myFunc)
{
   if(myFunc() == false)
   {
      // Show error
   }
}

You can then define your Func either as a method, or a lambda:

// Define a method
private bool MethodFunc() {}

// Pass in the method
Execute(MethodFunc)

// Pass in the Lambda
Execute(() => { return true; });

You don't nececssairly need to pass the parameters in as you can now access them from the caller's scope:

Execute(() => { return myBool; });
Execute(() => { return String.IsNullOrEmpty(myStr); });
Sign up to request clarification or add additional context in comments.

2 Comments

A Func<bool> is a function that returns bool without parameters, i.e. the same as a C++ Func<bool(void)> ?
But you can now access them via the calling lambda - so you don't explicitly need to define them on the method signature.
1

With my solution, you can perform any function, any input parameter, with any return, this is a very generic implementation

Example:

public T YourMethod<T>(Func<T> functionParam)
{
   return functionParam.Invoke();
}

public bool YourFunction(string foo, string bar, int intTest)
{
    return true;
}

Call like This specifying the return :

YourMethod<bool>(() => YourFunction("bar", "foo", 1));

Or like this:

YourMethod(() => YourFunction("bar", "foo", 1));

2 Comments

Why do you use Invoke to call the function, instead of calling it directly?
its more easy if you need to pass parameters
0
  without argument  do this 

  void Execute(Func<bool> fctn)
    {
        if(fctn() )
        {
            show_error();
        }
    }  

  with arguments you can do something like this:

    void Execute<T>(Func<T[],bool> fctn)
    {
        var v = new T[4];
        if(fctn(v) )
        {
            show_error();
        }
    }

1 Comment

How do I use that with a function that has parameters (the bind part)?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.