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 =>:
csharp1// Traditional method2static int Square(int n)3{4 return n * n;5}67// Expression-bodied method8static 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:
csharp1// Math operations2static int Add(int a, int b) => a + b;3static int Multiply(int a, int b) => a * b;4static double Half(double n) => n / 2;56// String operations7static string ToUpper(string s) => s.ToUpper();8static string Greet(string name) => $"Hello, {name}!";910// Boolean checks11static 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:
csharp1// Traditional2static void Print(string message)3{4 Console.WriteLine(message);5}67// Expression-bodied8static void Print(string message) => Console.WriteLine(message);910// More examples11static void SayHello() => Console.WriteLine("Hello!");12static void PrintLine() => Console.WriteLine(new string('-', 40));13static void Beep() => Console.Beep();
Multiple Parameters
csharp1static string FormatName(string first, string last)2 => $"{last}, {first}";34static double CalculateArea(double width, double height)5 => width * height;67static bool InRange(int value, int min, int max)8 => value >= min && value <= max;910static string CreateEmail(string user, string domain)11 => $"{user}@{domain}";
Complex Expressions
The expression can be complex, as long as it's a single expression:
csharp1// Ternary operator2static string GetStatus(bool active) => active ? "Active" : "Inactive";34static int Max(int a, int b) => a > b ? a : b;56static string Pluralize(string word, int count)7 => count == 1 ? word : word + "s";89// Null-coalescing10static string SafeGet(string? value) => value ?? "N/A";1112// Method chaining13static string Normalize(string text)14 => text.Trim().ToLower().Replace(" ", " ");1516// LINQ expressions17static 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:
csharp1// Don't try to cram this into expression body2static 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}1213// This is fine as expression body14static 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
csharp1static 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
csharp1static bool IsValidEmail(string email)2 => email.Contains("@") && email.Contains(".");34static bool IsValidAge(int age)5 => age >= 0 && age <= 150;67static bool IsValidUsername(string username)8 => username.Length >= 3 && username.Length <= 20;910static bool IsStrongPassword(string password)11 => password.Length >= 8 && password.Any(char.IsDigit);
Formatting
csharp1static string FormatCurrency(decimal amount)2 => amount.ToString("C2");34static string FormatPercent(double value)5 => (value * 100).ToString("F1") + "%";67static string FormatPhone(string digits)8 => $"({digits[..3]}) {digits[3..6]}-{digits[6..]}";910static string PadLeft(string s, int width)11 => s.PadLeft(width);
Calculations
csharp1static double CircleArea(double radius)2 => Math.PI * radius * radius;34static double CircleCircumference(double radius)5 => 2 * Math.PI * radius;67static double RectangleArea(double w, double h)8 => w * h;910static double TriangleArea(double baseLen, double height)11 => 0.5 * baseLen * height;1213static double Distance(double x1, double y1, double x2, double y2)14 => Math.Sqrt(Math.Pow(x2 - x1, 2) + Math.Pow(y2 - y1, 2));
Predicates
csharp1static bool IsPrime(int n)2 => n > 1 && Enumerable.Range(2, (int)Math.Sqrt(n) - 1)3 .All(i => n % i != 0);45static bool IsPalindrome(string s)6 => s.SequenceEqual(s.Reverse());78static bool ContainsDigit(string s)9 => s.Any(char.IsDigit);
Combining with Overloading
csharp1static 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();45static 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!