Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using another method as a parameter

Is there a way to use a method as a parameter for another. For instance, a method that returns 2f(3) for a given function f. I understand that as is, my code is incorrect: I'm trying to convey the idea that I want.

static double twofof3(double f(double x))
{
    return 2*f(3);
}

static double f(double x)
{
   return x * x;
}

The twofof3 method is currently pointless because it could be achieved with just the f method, but it's more the concept I am interested in.

like image 957
Wilson Avatar asked Aug 25 '26 07:08

Wilson


1 Answers

Yes, you can use a Func delegate:

static double twofof3(Func<double,double> f)
{
    return 2*f(3);
}

static double function1(double x)
{
   return x * x;
}

// ...

Console.WriteLine(twofof3(function1));
like image 195
Blorgbeard Avatar answered Aug 27 '26 22:08

Blorgbeard



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!