Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Call function with a parameter from another function

I have a function that repeatedly calls another function.

The second function has a bool parameter that changes the way it behaves, so when I call the first function I want to have a parameter that specifies the way the second function behaves.

void Function1(int n, bool differentBehavior = false)
{
    int a = Function2(n, differentBehavior);
    int b = Function2(1, differentBehavior);
    int c = Function2(2, differentBehavior);

    return a + b + c;
}

int Function2(int x, bool differentBehavior)
{
     if (!differentBehavior) // do something
     else // do something else
 }

The code itself is obviously an example (in reality the second function is called over 20 times and for code readability I would love to not have to specify the second parameter every time), but I put it there to explain what I’m currently doing. Is there no better way to achieve this?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

You can introduce a local function to capture the second argument like so:

int Function1(int n, bool differentBehavior = false)
{
    int func(int n) => Function2(n, differentBehavior);

    int a = func(n);
    int b = func(1);
    int c = func(2);

    return a + b + c;
}

This is called "partial function application". See more here:

https://codeblog.jonskeet.uk/2012/01/30/currying-vs-partial-function-application/

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading