❔ => operator
So I read while looking into LINQ documentation that
=>
is the syntax for a lambda expression. Now in the context of LINQ it makes sense, I would've guessed already. However in a class:
I would assume it is not seen as a lambda, it should just be a class method as its just syntax sugar for:
14 Replies
this is referred to as expression body syntax
so when its not declared to a name
like with
foo
hereright, the meaning depends on the context
you can also declare lambdas outside of linq fwiw
for example
Action myAction = () => { do something; };
Action
is the base type for any Lambda i assume?
()
captures any values you pass when calling the lambda
I assume it works similarly to a functionno,
Action
is a delegate type which is sort of a function pointer if you're familiar with C/C++, it specifically represents a function that has no parameters and returns nothing
but yes, lambdas are simply functions with no name
the left side of the =>
is the parameter list, captures are automatic(you can use
static
to avoid implicit captures)yes, in this case, it is an "expression-bodied member" https://learn.microsoft.com/en-us/dotnet/csharp/programming-guide/statements-expressions-operators/expression-bodied-members
Expression-bodied members - C# Programming Guide - C#
Learn about expression-bodied members. See code examples that use expression body definition for properties, constructors, finalizers, and more.
so:
std::function
essentially, with a bunch of overhead. Do they offer raw function pointers or is this all available to us in C#?
they arent a class/struct under the hood that overload operator()
like lambda's in C++?i haven't tried to use raw function pointers but if they exist you won't be able to use them outside of
unsafe
blocks of code
no, lambdas are compiled as a method in the type they're declared in with an unspeakable compiler-generated name
with an additional class to contain captures if anything is captured
(i think, this isn't something i really have to pay attention to in my current projects)SharpLab
C#/VB/F# compiler playground.
Technically yes, but jimmacle is right, they're only usable in unsafe code and should be avoided by most people
Thanks all, makes sense!
Was this issue resolved? If so, run
/close
- otherwise I will mark this as stale and this post will be archived until there is new activity.