Functional programming with C# - Func Delegates

C# also provides some delegate types for methods that return something and accept none, one, two or up to 16 arguments. It is called Func
This is the fifth 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, the third part about lambda or the fourth part about Action delegates I recommend you to learn about them before continuing.

By now you already understand what delegates are and how can you use them to store and pass void methods as arguments to execute something somewhere else.


Func Delegates

Action<T1,…T16> delegates are useful when we want to store or pass a reference to a method that does not return anything, but C# also provides delegate types for methods that return something, they are called Func and they also can accept none or up to 16 arguments like the Action delegate types. 

To illustrate it, let's change our scenario a little bit. Consider the following example where SmartClass now has a methods that do something smart with a sentence. One of these methods could take a sentence and return the same sentence but upper case and as a list of words.
Our DelegateExamples simply has a method that accepts a sentence and the reference to a function that does something to that sentence. Whatever happens to the sentence is not the concern of this method, its concern is to execute that function passing the same sentence it receives, and print the result of words on the console. The method accepted as argument is a Func<T1,TResult>, in our case Func<string, IEnumerable<string>>because it will take a string as input and it will produce an enumerable of string as result.
Notice that the method reference we are passing is actually on SmartClass, but we could pass any method as long as its functionality consists on accepting a string and returning an enumerable of strings. In fact we could even pass our own anonymous method using lambda as follows:
Our lambda expression takes one argument (we don't need its type because it will be inferred by the C# compiler) and it has to return an enumerable of string to comply with the delegate signature.

Find the examples on my GitLab repository

Comments