Functional programming with C# - Action Delegates

C# already provides some delegate types for methods that don't return any value and accept none, one, two or up to 16 arguments. It is called Action

This is the fourth part of the series about functional programming with C#. If you have not read through the first part about delegates, the second part about anonymous functions or the third part about lambda I recommend you to learn about them before continuing.

By now you already know how to create delegate types to store references to methods and how to use lambda expressions to create anonymous functions.


Action Delegates

We created a delegate type in SmartClass with the following line public delegate void WriteMessage(string message); to have a new type capable of storing references to methods that don't return anything and accept a single string argument.

However C# has already delegate types for this purpose and we should use them instead creating our own. In our case we would use an Action delegate (because Action delegates don't return anything) with one single argument Action<T>. We don't need the WriteMessage delegate anymore and we can replace it with the Action<T> being the type of the only argument T a string:

Modifying the delegate property outside does not seem a good practice because we could forget to do so or even some other thread could modify its value affecting our expected execution. To prevent side effects and as a good practice we can pass our method directly into the Divide method. That's right, we can pass methods as arguments! Isn't this a nice functional programming feature?

And since we have broken our Divide method signature by adding an additional argument, we now need to also modify the way we call this method.
Find the examples on my GitLab repository

Comments