C
C#14mo ago
joren

❔ => 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:
class A
{
int foo() => 34;
}
class A
{
int foo() => 34;
}
I would assume it is not seen as a lambda, it should just be a class method as its just syntax sugar for:
int foo() { return 34; }
int foo() { return 34; }
14 Replies
Jimmacle
Jimmacle14mo ago
this is referred to as expression body syntax
joren
jorenOP14mo ago
so when its not declared to a name like with foo here
Jimmacle
Jimmacle14mo ago
right, the meaning depends on the context you can also declare lambdas outside of linq fwiw for example Action myAction = () => { do something; };
joren
jorenOP14mo ago
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 function
Jimmacle
Jimmacle14mo ago
no, 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
Thinker
Thinker14mo ago
(you can use static to avoid implicit captures)
reflectronic
reflectronic14mo ago
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.
joren
jorenOP14mo ago
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++?
Jimmacle
Jimmacle14mo ago
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)
Jimmacle
Jimmacle14mo ago
you can play around in https://sharplab.io/ to see what the compiler does in terms of lowering
SharpLab
C#/VB/F# compiler playground.
333fred
333fred14mo ago
Technically yes, but jimmacle is right, they're only usable in unsafe code and should be avoided by most people
joren
jorenOP14mo ago
Thanks all, makes sense!
Accord
Accord14mo ago
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.
Want results from more Discord servers?
Add your server