Junior — Middle
Explain what anonymous functions or lambda expressions are in programming.
sobes.tech AI
Answer from AI
Anonymous functions or lambda expressions are functions without names that can be defined directly at the point of use. In C#, they allow writing concise code, especially when working with delegates, events, and LINQ.
A lambda expression is written using the => operator, where the parameters are on the left and the body of the function is on the right.
Example:
Func<int, int, int> sum = (a, b) => a + b;
int result = sum(3, 4); // result = 7
Here, (a, b) => a + b is a lambda expression that takes two parameters and returns their sum.
Anonymous functions are convenient for passing small blocks of code as parameters, for example, for sorting or filtering collections.