Delegates and lambda
Delegates and lambda
What are delegates?
A delegate is a type that represents a reference to a method (with a particular parameter list and return type). All delegates implicitly derive from System.Delegate
class. C# handles callback functions and event handlers by delegates. When you instantiate a delegate, you can associate its instance with any method with a compatible signature and return type. You can invoke (or call) the method through the delegate instance!
A simple demo to create and use a delegate
Using delegates with an anonymous method
In C# 1.0, you created an instance of a delegate by explicitly initializing it with a method that was defined elsewhere in the code. C# 2.0 introduced the concept of anonymous methods as a way to write unnamed inline statement blocks that can be executed in a delegate invocation.
Anonymous methods in C# can be defined using the delegate
keyword. By using anonymous methods, you reduce the coding overhead in instantiating delegates because you do not have to create a separate method.
Using delegates with lambda expressions
C# 3.0 introduced lambda expressions, which are similar in concept to anonymous methods but more expressive and concise. In general, applications that target version 3.5 and later of the .NET Framework should use lambda expressions. A lambda expression is a block of code (an expression or a statement block). It can be passed as an argument to methods, and it can also be returned by method calls! Lambda expression is a shorter way of representing anonymous methods.
A lambda expression uses =>
, the lambda declaration operator, to separate the lambda's parameter list from its executable code. To create a lambda expression, you specify input parameters (if any) on the left side of the lambda operator, and you put the expression or statement block on the other side.
Using delegates with lambda expressions with no parameters
There can be lambda expressions without any parameters and we can use local variables in the lambda expressions as shown in the below example:
Additional Reading
https://itnext.io/delegates-anonymous-methods-and-lambda-expressions-5ea4e56bbd05
Last updated