Wilson
Wilson

Reputation: 8768

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.

Upvotes: 3

Views: 81

Answers (1)

Blorgbeard
Blorgbeard

Reputation: 103535

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

Upvotes: 7

Related Questions