C
C#3w ago
Faker

✅ 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 please
9 Replies
Jimmacle
Jimmacle3w ago
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
Faker
FakerOP3w ago
The thing is, a delegate, defines a lambda function ?
Jimmacle
Jimmacle3w ago
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
Faker
FakerOP3w ago
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 expression
Jimmacle
Jimmacle3w ago
you 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)
Faker
FakerOP3w ago
ahhh okk make sense
Jimmacle
Jimmacle3w ago
lambdas are just a way to do that inline
Faker
FakerOP3w ago
that why we were able to use regular methods earlier yeahh I see It's clearer now, thanks !!
Jimmacle
Jimmacle3w ago
:pepeok:

Did you find this page helpful?