I’m pretty new to lambda expressions in C# and I tend not to use them because I don’t know what the benefits outside of minimizing code is. Are they more efficient in some/all cases? Or are there any fantastic things they can achieve beyond putting more code within one line?
Share
Lambda expressions are not more performant, they are just simpler. They are mainly used for:
When creating a delegate, the code that the compiler creates is just like if you would have created a named method, and got a delegate to that method.
compared to:
When creating an expression, the compiler creates an expression tree that can either be turned into a delegate or used by a LINQ provider to be translated into something else. The Linq To Sql provider for example would translate the expression into SQL code.
When creating a delegate that uses a local variable that is declared in the method that creates the deleage, a closure object is automatically created where that variable resides, instead of putting the variable on the stack. This is similar to how you would make the variable available to a named method by making it a field in the class where the method is declared.
compared to: