CONSTRUCTING FUNCTIONS DYNAMICALLY

Most of the C# functionality related to creating functions and methods has been around in programming languages for a long time. Many languages have also had the feature of variables that refer to functions. Even the C programming language had function pointers that could be used to store references to functions, pass these into other functions, and call into the functions. The C# 1.0 delegate type doesn’t really add much to what was already possible in C; the idea is just more formalized through the delegate keyword and has been extended upon with multicast delegates and events.

The main difference between C and C# from version 2.0 onward is that C# makes it possible to create new functions anonymously. Now you may wonder why this is so important — after all, the compiler inserts these functions as methods into the class, so isn’t this just syntactic sugar? To a certain extent that’s true, but there is a lot of functionality gained by the capability to create functions on-the-fly and return them to the outer scope. Yes, functions can be return values, just like this:

private static void ReturningFunctions( ) {

  var add = GetAdd( );

  var result = add(10, 20);

}

 

static Func<int, int, int> GetAdd( ) {

  return (x, y) => x + y;

}

Although appealing from a technical standpoint, this example doesn’t really solve any problems. The same function is returned from every call to GetAdd, which is nothing special and could be achieved much more easily. ...

Get Functional Programming in C#: Classic Programming Techniques for Modern Projects now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.