I have recently been using D3.js for some HTML5/SVG/Javascript work and suddenly realised how useful passing functions as parameters to methods is. I then thought, well how about C#. Here are some examples ….
This is the ubiquitous ‘Hello World’ example. Here a lambda function is passed as a parameter to a ‘Test’ method. The method makes a callback to the lambda function passing ‘Hello’ as a parameter. The lambda function now executes and concatenates ‘Hello’ with ‘ World’ and returns ‘Hello World’. This result is then passed back to the variable res. I like the way that we can influence the behaviour of a method without having to modify any code within it.
static void Main(string[] args) { string res = Test(2, d => d + " World"); Console.WriteLine(res); } public static string Test(int a, Func<string, string> f) { return f("Hello"); }
In the above example we used a Func to allow us to pass a variable to the function and get a result returned. In most cases you will not want a returned result. So use the Action instead. Here is an example..
static void Main(string[] args) { int a = 0; Test(d => { a = d * 3; }); Console.WriteLine(a); } public static void Test(Action<int> f) { f(7); }
The above methods are using the passed function as their principle subject. In the real world the function passed to a method would serve to add value or behaviours to the method.