➡️ Lambda-Style Everything
Simple methods with { return x; }? Verbose. Expression-bodied members use => for methods, properties, constructors. One line replaces five.
Expression-Bodied Methods
// ❌ Traditional method syntax
public string GetFullName()
{
return $"{FirstName} {LastName}";
}
// ✅ Expression-bodied method
public string GetFullName() => $"{FirstName} {LastName}";
// More examples
public int Add(int a, int b) => a + b;
public bool IsAdult() => Age >= 18;
public void PrintMessage() => Console.WriteLine("Hello");
public async Task GetUserAsync(int id) => await _repository.GetByIdAsync(id);
🎯 Expression-Bodied Properties
public class Person
{
public string FirstName { get; set; }
public string LastName { get; set; }
public DateTime BirthDate { get; set; }
// ❌ Traditional read-only property
public string FullName
{
get
{
return $"{FirstName} {LastName}";
}
}
// ✅ Expression-bodied property
public string FullName => $"{FirstName} {LastName}";
// More examples
public int Age => (int)((DateTime.Now - BirthDate).TotalDays / 365.25);
public bool IsAdult => Age >= 18;
public string Initials => $"{FirstName[0]}{LastName[0]}";
}
// Expression-bodied getter and setter (C# 7+)
private string _name;
public string Name
{
get => _name;
set => _name = value?.Trim() ?? throw new ArgumentNullException();
}
Expression-Bodied Constructors
public class Point
{
public int X { get; }
public int Y { get; }
// ❌ Traditional constructor
public Point(int x, int y)
{
X = x;
Y = y;
}
// ✅ Expression-bodied constructor
public Point(int x, int y) => (X, Y) = (x, y);
}
// More examples
public class Logger
{
private readonly ILoggerFactory _factory;
public Logger(ILoggerFactory factory) => _factory = factory ?? throw new ArgumentNullException(nameof(factory));
}
Expression-Bodied Finalizers & Indexers
// Expression-bodied finalizer
~MyClass() => Console.WriteLine("Finalizing");
// Expression-bodied indexer
public class Collection
{
private readonly T[] _items;
public Collection(T[] items) => _items = items;
// ❌ Traditional indexer
public T this[int index]
{
get { return _items[index]; }
set { _items[index] = value; }
}
// ✅ Expression-bodied indexer
public T this[int index]
{
get => _items[index];
set => _items[index] = value;
}
}
🔧 Complete Class Example
public class Product
{
public int Id { get; set; }
public string Name { get; set; }
public decimal Price { get; set; }
public decimal Cost { get; set; }
public int Stock { get; set; }
// Expression-bodied properties
public decimal Margin => Price - Cost;
public decimal MarginPercent => (Margin / Price) * 100;
public bool InStock => Stock > 0;
public bool LowStock => Stock < 10 && Stock > 0;
// Expression-bodied methods
public decimal CalculateRevenue(int quantity) => Price * quantity;
public decimal CalculateProfit(int quantity) => Margin * quantity;
public bool CanFulfillOrder(int quantity) => Stock >= quantity;
public void Restock(int amount) => Stock += amount;
public void Sell(int quantity) => Stock -= quantity;
// ToString
public override string ToString() => $"Product: {Name} (${Price:F2})";
}
// Usage
var product = new Product
{
Name = "Widget",
Price = 100m,
Cost = 60m,
Stock = 50
};
Console.WriteLine(product.Margin); // 40
Console.WriteLine(product.MarginPercent); // 40
Console.WriteLine(product.LowStock); // false
Console.WriteLine(product.CalculateProfit(10)); // 400
✅ When to Use
- Single-expression methods: One return statement
- Read-only properties: Computed values
- Simple getters/setters: Validation, transformation
- Factory methods: new Constructor(params)
- LINQ projections: Clean Select() statements
⚠️ When NOT to Use
- Multiple statements: Stick to traditional syntax
- Complex logic: Readability over conciseness
- Long expressions: Line gets too long (> 120 chars)
- Debugging: Can’t set breakpoint inside expression
💡 Before & After Comparison
// ❌ Before: 30 lines
public class Calculator
{
public int Add(int a, int b)
{
return a + b;
}
public int Subtract(int a, int b)
{
return a - b;
}
public int Multiply(int a, int b)
{
return a * b;
}
public double Divide(int a, int b)
{
return (double)a / b;
}
public bool IsEven(int number)
{
return number % 2 == 0;
}
public int Square(int number)
{
return number * number;
}
}
// ✅ After: 10 lines
public class Calculator
{
public int Add(int a, int b) => a + b;
public int Subtract(int a, int b) => a - b;
public int Multiply(int a, int b) => a * b;
public double Divide(int a, int b) => (double)a / b;
public bool IsEven(int number) => number % 2 == 0;
public int Square(int number) => number * number;
}
// 67% less code, same functionality!
“Refactored utility classes to expression-bodied members. Code reduced 40%. Readability improved. Team adopted it everywhere. Now standard in our style guide.”
