I often hear developers say C# functions are very powerful. Having heard this so often I believe it is true but having not used functions too often I still don’t understand where their power lies. I have two questions:
1) What is the true power of C# functions, where can they be applied?
2) Aren’t normal methods the same as functions, for example what is the difference with the two below:
public int GetNumberOfDays(int randomVariable);
and
Func<int,int>
Func<int, int>is a delegate type that represents a method that takes one parameter of typeintand returns anint. Delegates are powerful: they allow you to pass one or more functions to another function. Delegates have other powers as well, but I will ignore them for this discussion.Passing a function to another function is a key concept with Linq to Objects:
In this case, we are using the
Selectmethod, which takes a sequence and a function and returns the sequence that results from applying the function to each member of the input sequence.In the example above,
TimesTwoandTimesThreeare passed to the Select method by virtue of “implicit method group conversion”. In short, the compiler converts the bare method name to a delegate that refers to the correct overload of the method. The term is “method group” because when a method is overloaded, the name refers to all of the overloads as a group, and the compiler must choose the correct overload.It can be inconvenient to write several methods simply because we want to pass them to other methods. That’s why C# introduced anonymous delegates and, later, the more concise lambda expression. Now, suppose we want to be able to quadruple our sequence in addition to doubling or tripling it. Instead of writing a new function called
TimesFour, we can use a lambda:Finally, we could make a more generic
TransformTheSequenceInSomeArbitraryMannermethod:That example is obviously just a trivial wrapper around the
Selectmethod, but it serves to illustrate how you would declare a method that takes aFunc<int, int>parameter. This method shows two ways of using that parameter:Specifically, you can invoke a delegate either by calling its
Invokemethod explicitly, or with method-call syntax. The compiled code is identical for either approach.Finally, to answer your question:
The first is a method declaration; it declares a specific method that takes an
intargument and returns a specificintwhose value presumably depends on the value of the argument. The second is a delegate type that can hold a reference to any method with the same signature.