Expression-bodied lambdas let you write short functions in a simple, clean way using just one expression.
0
0
Expression-bodied lambdas in C Sharp (C#)
Introduction
When you want to write a quick function that returns a value without many lines.
When you need to pass a small function as an argument to another method.
When you want to make your code easier to read by avoiding extra braces and return statements.
Syntax
C Sharp (C#)
(parameters) => expression
The expression after the arrow is the value returned automatically.
No need for curly braces or explicit return keyword for single expressions.
Examples
A lambda that takes one parameter x and returns x squared.
C Sharp (C#)
x => x * x
A lambda that takes two parameters and returns their sum.
C Sharp (C#)
(a, b) => a + b
A lambda with no parameters that returns the current date and time.
C Sharp (C#)
() => DateTime.Now
Sample Program
This program shows three expression-bodied lambdas: one to square a number, one to add two numbers, and one to return a greeting message.
C Sharp (C#)
using System; class Program { static void Main() { Func<int, int> square = x => x * x; Func<int, int, int> add = (a, b) => a + b; Func<string> greet = () => "Hello!"; Console.WriteLine(square(5)); Console.WriteLine(add(3, 4)); Console.WriteLine(greet()); } }
OutputSuccess
Important Notes
Expression-bodied lambdas are great for simple logic but use regular lambdas with braces for multiple statements.
They help keep your code short and easy to read.
Summary
Expression-bodied lambdas use a single expression after the arrow to return a value.
They simplify writing short functions without braces or return statements.
Useful for quick, readable code especially when passing functions as arguments.