8 minlesson

Expression-Bodied Methods

Expression-Bodied Methods

Expression-bodied methods provide a concise syntax for simple methods using the arrow (=>) notation.

Basic Syntax

Instead of a block with braces and return, use =>:

csharp
1// Traditional method
2static int Square(int n)
3{
4 return n * n;
5}
6
7// Expression-bodied method
8static int Square(int n) => n * n;

Both are equivalent, but the expression-bodied version is more concise.

When to Use Expression Bodies

Use them for simple, single-expression methods:

csharp
1// Math operations
2static int Add(int a, int b) => a + b;
3static int Multiply(int a, int b) => a * b;
4static double Half(double n) => n / 2;
5
6// String operations
7static string ToUpper(string s) => s.ToUpper();
8static string Greet(string name) => $"Hello, {name}!";
9
10// Boolean checks
11static bool IsEven(int n) => n % 2 == 0;
12static bool IsPositive(int n) => n > 0;
13static bool IsEmpty(string s) => string.IsNullOrEmpty(s);

void Methods

Expression-bodied syntax also works for void methods:

csharp
1// Traditional
2static void Print(string message)
3{
4 Console.WriteLine(message);
5}
6
7// Expression-bodied
8static void Print(string message) => Console.WriteLine(message);
9
10// More examples
11static void SayHello() => Console.WriteLine("Hello!");
12static void PrintLine() => Console.WriteLine(new string('-', 40));
13static void Beep() => Console.Beep();

Multiple Parameters

csharp
1static string FormatName(string first, string last)
2 => $"{last}, {first}";
3
4static double CalculateArea(double width, double height)
5 => width * height;
6
7static bool InRange(int value, int min, int max)
8 => value >= min && value <= max;
9
10static string CreateEmail(string user, string domain)
11 => $"{user}@{domain}";

Complex Expressions

The expression can be complex, as long as it's a single expression:

csharp
1// Ternary operator
2static string GetStatus(bool active) => active ? "Active" : "Inactive";
3
4static int Max(int a, int b) => a > b ? a : b;
5
6static string Pluralize(string word, int count)
7 => count == 1 ? word : word + "s";
8
9// Null-coalescing
10static string SafeGet(string? value) => value ?? "N/A";
11
12// Method chaining
13static string Normalize(string text)
14 => text.Trim().ToLower().Replace(" ", " ");
15
16// LINQ expressions
17static int Sum(int[] numbers) => numbers.Sum();
18static double Average(int[] numbers) => numbers.Average();

When NOT to Use Expression Bodies

Avoid for methods with multiple statements:

csharp
1// Don't try to cram this into expression body
2static void ProcessData(string[] data)
3{
4 foreach (var item in data)
5 {
6 Console.WriteLine($"Processing: {item}");
7 ValidateItem(item);
8 SaveItem(item);
9 }
10 Console.WriteLine("Done!");
11}
12
13// This is fine as expression body
14static void ProcessData(string[] data)
15 => Array.ForEach(data, item => Console.WriteLine(item));
16// But only if it truly is a single operation

Practical Examples

Temperature Conversions

csharp
1static double CelsiusToFahrenheit(double c) => c * 9 / 5 + 32;
2static double FahrenheitToCelsius(double f) => (f - 32) * 5 / 9;
3static double CelsiusToKelvin(double c) => c + 273.15;
4static double KelvinToCelsius(double k) => k - 273.15;

Validation Functions

csharp
1static bool IsValidEmail(string email)
2 => email.Contains("@") && email.Contains(".");
3
4static bool IsValidAge(int age)
5 => age >= 0 && age <= 150;
6
7static bool IsValidUsername(string username)
8 => username.Length >= 3 && username.Length <= 20;
9
10static bool IsStrongPassword(string password)
11 => password.Length >= 8 && password.Any(char.IsDigit);

Formatting

csharp
1static string FormatCurrency(decimal amount)
2 => amount.ToString("C2");
3
4static string FormatPercent(double value)
5 => (value * 100).ToString("F1") + "%";
6
7static string FormatPhone(string digits)
8 => $"({digits[..3]}) {digits[3..6]}-{digits[6..]}";
9
10static string PadLeft(string s, int width)
11 => s.PadLeft(width);

Calculations

csharp
1static double CircleArea(double radius)
2 => Math.PI * radius * radius;
3
4static double CircleCircumference(double radius)
5 => 2 * Math.PI * radius;
6
7static double RectangleArea(double w, double h)
8 => w * h;
9
10static double TriangleArea(double baseLen, double height)
11 => 0.5 * baseLen * height;
12
13static double Distance(double x1, double y1, double x2, double y2)
14 => Math.Sqrt(Math.Pow(x2 - x1, 2) + Math.Pow(y2 - y1, 2));

Predicates

csharp
1static bool IsPrime(int n)
2 => n > 1 && Enumerable.Range(2, (int)Math.Sqrt(n) - 1)
3 .All(i => n % i != 0);
4
5static bool IsPalindrome(string s)
6 => s.SequenceEqual(s.Reverse());
7
8static bool ContainsDigit(string s)
9 => s.Any(char.IsDigit);

Combining with Overloading

csharp
1static int Max(int a, int b) => a > b ? a : b;
2static int Max(int a, int b, int c) => Max(Max(a, b), c);
3static int Max(params int[] numbers) => numbers.Max();
4
5static string Join(string a, string b) => a + b;
6static string Join(string a, string b, string c) => Join(Join(a, b), c);
7static string Join(params string[] parts) => string.Join("", parts);

Summary

In this lesson, you learned:

  • Expression-bodied syntax uses => instead of braces and return
  • Use for simple, single-expression methods
  • Works for both returning methods and void methods
  • Makes code more concise and readable
  • Avoid for complex methods with multiple statements

Now let's practice with hands-on workshops!