✅ Delegate vs lambda function/expression
Hello guys, I was just reading a bit about delegates and lambda expression. I thought that lambda expression and delegates were the same thing. For example, when I see something like:
Func<int,int>
.... is it a delegate? When such syntax appears in a method like in LINQ, there, what do we expect? Normally, we wrote something like s => s.DoSomething()
I'm a bit confused, what makes each one different from the other and when to recognise them please9 Replies
lambda is the name for an anonymous method, a delegate is the "type" of a method and can be used to store/pass methods as variables
you can pass both lambdas and regular methods when calling LINQ methods, for example
The thing is, a delegate, defines a lambda function ?
a delegate has no specific relationship to lambdas
a lambda is just a method with no name
a delegate is a data type
since lambdas are anonymous they can only effectively be used when assigned to a variable or passed as an argument
incidentally, delegates are how you store methods in variables
yeah I see, hmm the thing is, when I hover oversome methods, I have syntax like this:
SetProperty<TProperty>(Func<Car, TProperty>, TProperty)
So here basically we need to replace Func<...>
by a lambda expressionyou don't
you can pass any method that is compatible with the delegate type (in this case, has one argument that accepts a
Car
and returns a TProperty
)ahhh
okk make sense
lambdas are just a way to do that inline
that why we were able to use regular methods earlier
yeahh I see
It's clearer now, thanks !!
:pepeok: