Assigning Lambda to Delegate (PurposesReason)
Based on my (possibly incorrect) understanding, delegates are the variables to which lambda expressions are assigned.
https://stackoverflow.com/a/73819
Also based on my understanding (possibly incorrect), assigning a lambda to a delegate in this way makes it possible to pass said delegate/lambda expression into another method as an input parameter.
My question is, what are the advantages of passing lambda logic into other method with delegates?
Is it solely to promote reusability of code?
Or are there other advantages to it?
Stack Overflow
What is the difference between lambdas and delegates in the .NET Fr...
I get asked this question a lot and I thought I'd solicit some input on how to best describe the difference.
6 Replies
Are you asking about the reason to use delegates or lambdas?
lambdas can also capture state from the scope in which they are declared (a "closure") which can be useful.
In general, it's useful to pass code around as an abstraction. Consider everyone's favorite functional code, LINQ. If you had to re-implement
Select
and Where
and all the rest of LINQ for every type of IEnumerable, you'd be a very sad programmerLambdas let you write a function inline without defining an actual, full method to do that work. Assigning a lambda to a delegate lets you reuse the same delegate instance multiple times, which is useful for example with event subscriptions. This is pseudocode and probably wouldn't actually compile, but I find that wrapping the event-based async pattern with the task-based async pattern is a great use for this.
Kind of both actually, I'm not too clear on the distinction
@surwren
Adding to all amazing answers
A delegate is just a type can hold a reference to a method, do give an example of why a delegate would be useful take this example
When
PerformeClick
is called on _start OnStart
get's invoked, is really helpful because now you can make execute your own code when a Button
is clicked, or you can swap what's getting executed (in the case of the example about, that can't happen because Button._onClick
is private and can't be set anywhere but I hope you get the point)
Mow for lambdas, they are anonymous functions (and can be closures)
let's take another example
Now we can easily do
This greatly helps with abstraction, instead of having to define every single predicate as a method
I forgot to mention, you can use Action
and Func
as a substitute for declaring your own delegates