Junior — Middle
When is it appropriate to use anonymous functions in code?
sobes.tech AI
Answer from AI
Anonymous functions (lambda expressions) in C# are useful when you need to quickly define a small function without the need to create a separate named method. They are convenient for passing functions as arguments, especially in LINQ queries, event handlers, and when working with collections.
Example of using an anonymous function with LINQ:
var numbers = new List<int> {1, 2, 3, 4, 5};
var evenNumbers = numbers.Where(n => n % 2 == 0).ToList();
Here, n => n % 2 == 0 is an anonymous function that returns true for even numbers. This makes the code compact and readable.