Expression-bodied members introduce a concise syntax that lets you define methods and properties using lambda arrow notation instead of traditional code blocks.
Property Implementation
Consider a class that needs a property with validation logic. Instead of writing full getter and setter blocks, you can express them as lambda expressions:
public class Customer
{
private string email;
public string Email
{
get => email;
set => email = value ?? throw new ArgumentException(nameof(value));
}
}
The get => email syntax returns the field value directly. The set => email = value ?? ... syntax performs validation before assignment, throwing an exception if null is provided.
Read-Only Computed Properties
Expression-bodied members shine brightest when defining read-only properties that compute values:
public class Rectangle
{
private double width;
private double height;
public double Area
{
get => width * height;
}
public double Circumference => 2 * (width + height);
}
The Circumference property demonstrates the shorthand syntax where the entire property definition fits on a single line after the => operator. This eliminates the need for braces and the return keyword for single-expression properties.
Method Implementation
Methods can also leverage this syntax for simple one-liner implementations:
public class MathHelper
{
public int Multiply(int x, int y) => x * y;
public double ToRadians(double degrees) => degrees * Math.PI / 180.0;
}
For more complex logic, traditional block syntax remains necessary:
public class Validator
{
public bool IsEven(int number)
{
if (number < 0) number = -number;
return number % 2 == 0;
}
public bool IsPowerOfTwo(int n)
{
if (n < 1) return false;
return (n & (n - 1)) == 0;
}
}
Constraints
Expression-bodied members work only for members that evaluate to a single expresion. Multi-statement logic, try-catch blocks, and complex control flow still require traditional code block definitions. When ipmlementing validators or computationally intensive operations, prefer explicit block syntax for readability and maintainability.