C# .Net Anonymous Functions, Lambda Expression & Delegates(Func) Relationship and Quick Reference
In modern Asp.Net Core web applications/api we usually see something like
routes => {routes.MapRoute("default"
{controller=Home}/{action=Index}/{id?}"); }
Well i am going too far away we see it all over when using Linq
Cities.Where(x=>x.Population > 155000)
The expression (x=>x.Population > 155000) is called lambda expression. Alot of beginners can understand and use the above expression but they get really confused when we talk about Delegates, Funcs etc. And it is totally okay because Language is evolving all the time and the one starting in 2018 can’t understand all the history in few months.
I will try to keep this article short and try to write it as a quick mini reference.
Following topics will be discussed
- Anonymous Functions
- Delegates, Func, Actions
- Lambda Expressions
- Named Method
- Relationship between all of the above topics and their usage
Delegates
Delegate is a type which points to a method. You can assign a method to a delegate and then pass it to another method as argument. They are something similar to function pointers in C++. Delegate has a signature and a return type. Any method with similar return type and signature can be assigned to it.
Delegate With Named Method
You may see something like this legacy code(Before C# 2.0)
C#2.0+ provides a more simpler way for the initialization/assignment
Anonymous Functions
Sometimes we don’t need to reuse the methods in that case we prefer to use something shorter cleaner and inline. Anonymous functions are inline expressions/statements.
There are two types of Anonymous functions in C#
1. Anonymous Methods
C#2.0 introduced anonymous methods. Instead of using named method as above we can use delegate keyword for these unnamed anonymous methods.
2. Lambda Expressions
C# 3.0 introduced lambda expressions. A more simple way to write anonymous functions
The following expressions produce same results. Just a different way of writing
Func Delegate
Func Delegate is there to make things easy for you. Instead of defining custom delegate you can use this generic Func Delegate. Func has various argument options but important thing to remember is
- Func returns a value
- Last parameter is a return value. Others are input
Action Delegate
Action delegate is similar to Func delegate except that it does not return any value. It is used when the return type is void Action<int,int>
All In Action Code Snippet
So now you can see that all of them are pretty linked to each other and they are used almost every where. Linq methods require type of Func Delegate. ForEach() method requires Action Delegate and the list goes on. But now you can understand that what was the history behind Func<> when you see it in IntelliSense
Ref/Other Relevant Topics