How do you write and use a lambda expression as a shorthand for a delegate?
Short answer
A lambda expression `(parameters) => expression` provides a concise, inline way to define a small function without a separate named method declaration — it can be assigned directly to any compatible delegate type, including built-in ones like Func<> and Action<>.
Advertisement
AModel answer
A lambda expression `(parameters) => expression` provides a concise, inline way to define a small function without a separate named method declaration — it can be assigned directly to any compatible delegate type, including built-in ones like Func<> and Action<>.
Func<int, int, int> add = (a, b) => a + b;
Console.WriteLine(add(3, 4)); // 7
Action<string> greet = name => Console.WriteLine($"Hello, {name}");
greet("Sam");Real-world example
Passing a short, inline comparison or filtering expression directly to a LINQ method like Where() or OrderBy().
Likely follow-ups
- What's the difference between the built-in Func<> and Action<> delegate types?
Related topics