Hello Code Project Gurus
I know it is possible to have delegates operate with values that are known at the time the delegate is called - that's simply a parameter
e.g.
Func<double, double> areaOfCircle = r => Math.PI * Math.Pow(r, 2);
Func<double, double> diameterOfCircle = r => 2 * Math.PI * r;
var iNeed = diameterOfCircle;
Console.WriteLine(iNeed(5));
Console.WriteLine(iNeed(10));
iNeed = areaOfCircle;
Console.WriteLine(iNeed(5));
Console.WriteLine(iNeed(10));
I am wondering if there is any way to dynamically create delegates so that each delegate operates using values that are known at runtime when the delegate is created (not when the delegate is called).
So, using the example above, is there a way tell areaOfCircle to use some other factor rather than pi? Something akin to
Func<double, double> areaOfCircle = r => ::factor:: * Math.Pow(r, 2);
Func<double, double> diameterOfCircle = r => 2 * ::factor:: * r;
var iNeed = diameterOfCircle(factor::3);
Console.WriteLine(iNeed(5));
Console.WriteLine(iNeed(10));
iNeed = areaOfCircle(factor::3.14);
Console.WriteLine(iNeed(5));
Console.WriteLine(iNeed(10));
Again, I know that a simple example like this is easily solvable by passing the factor to each function in the Console.WriteLine calls. But instead, imagine that the assignment to iNeed and the calls to iNeed are occurring in separate methods, or even classes; that once iNeed is assigned, it is passed as the return value to a calling class that sticks it in a List, which gets called by another class to execute the function... normal, everyday type of stuff.
What I am looking for is a way to set up the functions to operate with a certain factor when the assignment to iNeed is made. Is such a thing possible?
What I have tried:
Searching the net.
Reading MS documentation on delegates, anonymous delegates, dynamic variables, etc.