Did you ever think why anonymous functions, lambdas, Func were introduced? Maybe they are somehow connected with each other? If you are interested, read on, I tried to answer this questions below in very concise examples.
Delegate
In the beginning was the delegate 🙂 Think about delegate as a kind of proxy which will take some parameter and send it to a method(s) which subscribes to this proxy (delegate). If you are not familiar with delegate concept look it up somewhere on the web, or read about it in those great books: Pro C# (detailed) C# in a Nutshell (concise).
In lines below:
1 – declare delegate with name Calculator
. You can use it with any method which returns and takes one int
parameter
2 – declare simple method Square
7 – subscribing Square
method to Calculator
delegate. Thanks to that in line:
8 – we can call delegate, which in effect will call Square method functionality.
delegate int Calculator(int x); public static int Square(int x) => x * x; static void Main(string[] args) { //Shorthand of Calculator = new Calculator(Square) Calculator c = Square; int result = c(3); }
Anonymous function
In most cases we do not need methods assigned to delegates in other part of application, so why should we declare them at all? Anonymous methods let us handle that, so we do not need to declare Square
method anymore because we will pass functionality directly to delegate.
delegate int Calculator (int x); static void Main(string[] args) { Calculator c = delegate (int x) { return x * x; }; int result = c(3); }
Lambda
Lambdas allow you to simplify anonymous function call even more. However we still need to declare delegate.
delegate int Calculator (int x); static void Main(string[] args) { Calculator c = x => x * x; int result = c(3); }
Func
Ok, everything works and our code is quite clean. However let’s think about presence of delegate in that code. Will we use that part of code anywhere else? There is high chance that you dont. So why not get rid of it? Language creators helped us with that by creating  Func<T,TResult>
delegate.
Function delegate is generic delegate available in System
namespace which allows you to declare and use delegate in place of usage, which can simplify lambda example to this:
static void Main(string[] args) { Func<int, int> t = x => x * x; int result = t(3); }
Isn’t it cool ? 🙂
Check out also Action<T>
delegate which can be used with methods which take parameter(s) but return void.