5

As input to another program I am using I need to input a delegate of the form:

Func<double, double, double>.

I want the function to be sent in to be

F(a,b)=a+b*c+d

where c and d are known constants known at runtime.

So what I need is some method which takes the values c and d, and then gives me a function F(a,b). What I think I need to do is to first create the method:

double der(double a, double b, double c, double d)
{
   return a + b * c + d;
}

And from this method I have to do something with delegates in order to get my function. Do you see how to solve this problem?

1
  • 2
    Be careful that Func<double,double,double> does not describe a function that takes 3 double as parameters, but rather a function that takes 2 double and returns a double Commented Feb 27, 2019 at 13:11

1 Answer 1

7

You need to define the return value as your expected Func:

Func<double, double, double> MakeFunction(double c, double d)

now you can use a lambda expression to construct the function that you desire:

return (a,b) => a + b * c + d;

Explanation:

the (a,b) denote the input parameters for your function. As the designated return value in the method signature specifies that this will be 2 parameters of type double. the part after the => denotes the calculation that will be performed.

Now you can use it in the following way:

var myFunc = MakeFunction(3, 4);    
Console.WriteLine(myFunc(1, 2));

TEST Code:

double a = 1;
double b = 2;
double c = 3;
double d = 4;
var myFunc = MakeFunction(c, d);
Console.WriteLine("Func: " + myFunc(a, b));
Console.WriteLine("Direct test: "a + b * c + d);

OUTPUT:
Func: 11
Direct test: 11

2
  • 1
    Thank you very much, I have to learn how to use lambda expressions.
    – user394334
    Commented Feb 27, 2019 at 13:16
  • 1
    @user394334 you're welcome. have fun, it is a very interesting topic
    – Mong Zhu
    Commented Feb 27, 2019 at 13:18

Not the answer you're looking for? Browse other questions tagged or ask your own question.