Reputation: 277
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?
Upvotes: 5
Views: 475
Reputation: 23732
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
Upvotes: 7