I'm been wanting to create a user control, but before I do I need to know how to do a few things or even if its possible. I know it possible to pass a method to a function (Link). Is it possible to set a variable that is of function type? For example I have a user control where in one function I need to call GetData function. Each GetData routine is different so I was wondering if its possible to pass that function in from the aspx.cs page?
Asked
Active
Viewed 301 times
-3
-
2Your question is very broad and vague. I'm guessing the terms you're looking for are "delegate" and "event handler". Consider reading up on these then ask a more specific question. – Bob Kaufman May 10 '12 at 22:23
-
Thanks Bob. I will look into that. If I can pass a function into a private variable in a user control. Then I would be good. Thanks again. – MindGame May 10 '12 at 22:28
1 Answers
1
The .NET Framework Library defines handy generic delegates (or "function types" as you call it). Function delegates that have a return value
Func<Ret>
Func<Arg, Ret>
Func<Arg1, Arg2, Ret>
...
Function delegates that have no return value
Action<>
Action<Arg>
Action<Arg1, Arg2>
...
You can define a method that accepts a delegate like this
void DrawFunction(Func<double, double> function, double x0, double x1)
{
const double step = 0.1;
for (x = x0; x <= x1; x += step) {
double y = function(x);
DrawPointAt(x, y);
}
}
You can call it by either passing it an appropriate method or with a lambda expression.
Using this declaration
public double Square(double x)
{
return x*x;
}
You can do the call (note that the parentheses () are missing after Square
since we do not want to call this method here)
DrawFunction(Square, 0.0, 10.0);
You get the same result with a lambda expression
DrawFunction(x => x*x, 0.0, 10.0);

Olivier Jacot-Descombes
- 104,806
- 13
- 138
- 188