Please don't be confuse with the code, the code is wrong. Focused on the bold question below.
I've been preparing to study functional programming and just so at least be ready for its prerequisites, I've been studying extensions, functions and lambda expressions.
This code below is NOT working I just thought this is how it should be coded:
Program:
class Program
{
static void Main(string[] args)
{
int s = 10;
int t = s.CreatedMethod(2, 3); // <-- the one that calls the extension
Console.WriteLine(t.ToString());
Console.ReadLine();
}
static int RegularMethod(int v1, int v2)
{
return v1 * v2; // <-- I also wanted to multiply int 's' like this s*v1*v2
}
}
Extension:
public static class Extension
{
public static int CreatedMethod(this int number, Func<int, int, int> fn)
{
// I'm expecting that the code here will read the
// RegularMethod() above
// But I don't know how to pass the parameter of the function being passed
return @fn(param1, param2)// <-- don't know how to code here ??
}
}
As you can see, the CreateMethod extended my integer 's'. My plan is to pass the two parameters in CreateMethod() above and multiply those two parameters into 's'
In the example above, the answer should be 60.
Can you help me do it using extension?
Extension could look like this:
public static int CreatedMethod(this int number1, int number2, Func<int, int, int> fn) {
fn(number1, number2);
}
And then call would be:
var s = 10;
var t = s.CreatedMethod(2, RegularMethod).
CreatedMethod(3, RegularMethod);
This will first call RegularMethod
with 10
and 2
and second time with 20
and 3
.
Additional way would be to use extension like
public static int CreatedMethod(this int number1, int number2, int number3, Func<int, int, int> fn) {
fn(fn(number1, number2), number3);
}
And call like
var s = 10;
var t = s.CreatedMethod(2, 3, RegularMethod);