Functional programming with C# - Anonymous Functions

Anonymous functions are useful when a function does not need to be used by anybody else

This is the second part of the series about functional programming with C#. If you have not read through the first part about delegates I recommend you to learn about it before continuing.

By now you understand what delegates are and how can we use delegates to store references to methods so that we can delegate some tasks.


Anonymous Functions

Sometimes, when storing the reference to a method in a delegate type, like in our WriteMessage from the previous example, we don't need to have the method already somewhere in the code because maybe we just want to execute a piece of code that won't be used by anybody else. In other words, we want to write a method inline because this method is going to be used only once, and since nobody else needs to reference it we don't even need to give this method a name, it can be an anonymous method
Notice how the first method I am storing in the MethodAddress property is still the reference to the WriteInConsole method. But the second method that I want the Divide functionality to execute is an anonymous method created with the delegate keyword. It is anonymous because it has no name. If you run this code you will see that the WriteInConsole method is executed first and immediately after the anonymous method will be executed. The result will be:

Inside WriteInConsole method: 
Cannot divide by zero 
Inside an anonymous function: 
Cannot divide by zero

Find the examples on my GitLab repository

Comments