Skip to content
Tutorials Center
My learning

Topics

Lesson 37 of 182 ยท Methods

Expression-Bodied Members and Local Functions

Learn C# expression-bodied members with =>, throw expressions, local functions, static local functions, closures versus static, and recursion inside local functions, with runnable examples.

Many methods are one line long: return the square, return the full name, check a flag. Writing braces, a return keyword and three extra lines for each of them hides the interesting part. Expression-bodied members replace the braces and return with => (read it as "gives" or "is"), so the code shows only what the member computes.

The second half of this lesson is about local functions: small methods declared inside another method, where only that method can see them. They keep helper logic next to the code that uses it, and they can do things lambdas can't, like recursion without ceremony. We finish with the difference between local functions that capture variables (closures) and static local functions that cannot, and why it matters. It continues from Methods and links forward to Lambda Expressions.

The => syntax

If a method's body is a single expression, you can write it as ReturnType Name(parameters) => expression;. For a void method the expression is a statement-like call. The result is exactly the same compiled code as the block form, only shorter.

C# Expression-bodied methods

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

Expression bodies work for almost every kind of member:

Member Example
method public int Double(int x) => x * 2;
read-only property public string FullName => $"{First} {Last}";
property accessors get => _value; set => _value = value;
constructor public Person(string name) => Name = name;
indexer public int this[int i] => _items[i];
operator public static Money operator +(Money a, Money b) => new(a.Amount + b.Amount);
finalizer ~Resource() => Release();
C# Expression-bodied properties, constructors and operators

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

A property like FullName => ... has no storage: the expression runs every time you read it. That is perfect for cheap, derived values. It is the wrong choice for an expensive computation you do not want to repeat; cache that in a field instead. Note the difference between public int Id => 5; (a getter that computes) and public int Id { get; } = 5; (an auto-property initialized once). They look alike and behave differently when the expression is not a constant.

Throw expressions

throw can be used as an expression in a few places, which makes => bodies and null checks tidy: in ??, in ?:, and as a whole expression body. This became legal in C# 7.

C# throw expressions

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

When => helps and when it hurts

Use it for short, obvious members: one expression that fits on a line or two. Stop when you notice any of these:

  • the expression needs a long chain of ?: or &&/||;
  • you want to name an intermediate result (use a block body and a local variable instead);
  • you are tempted to put side effects in a property getter.

Readability decides. A block body is never "wrong", and a three-line => method with a nested ternary is not clever, it is a puzzle.

Local functions

A local function is a method declared inside another method (or constructor, property accessor, lambda...). It can be called only from within the enclosing member, and it is visible throughout that member's body, even from statements that come before its declaration. Write it just like a method, without an access modifier:

C# A first local function

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

Notice that Money reads the outer parameter currency directly. A local function can use the variables of its enclosing method; this is called capturing, and a function that captures is a closure.

Why use a local function and not a private method? When the helper is only meaningful for one method, a local function keeps it next to its only caller, stops it from being used elsewhere by mistake, and lets it share the outer variables without extra parameters. Why not a lambda? Local functions are named, can be recursive without tricks, support yield, attributes and generic parameters, and avoid allocating a delegate when you just call them directly.

Validate eagerly, iterate lazily

A classic use is splitting argument checks from an iterator method. An iterator (yield return) does not run any of its code until the first MoveNext, so a check at its top fires late, perhaps far from the bad call. A local iterator function fixes this:

C# Eager validation with a local iterator

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

The same trick works for async methods and anywhere you want checks to run synchronously before deferred work starts. Deferred execution is the topic of Deferred Execution and LINQ Pitfalls and Iterators and yield.

Closures and static local functions

When a local function reads or writes variables of its enclosing method, the compiler must keep those variables alive and shared. It generates a hidden helper type (a closure class or a struct) to hold them. Local functions that are only called are compiled to a struct passed by reference, so they usually cost nothing; but a closure used as a delegate (passed to List.Sort, stored in a field, returned) allocates an object.

Capturing is also a source of surprising bugs, because the local function sees the variable itself, not a snapshot of its value:

C# Captured variables are shared

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

If you want a local function to be pure (depend only on its parameters) and to be unable to capture by accident, mark it static (C# 8). The compiler then rejects any reference to the enclosing method's locals, parameters or this:

C# A static local function cannot capture (fails on purpose)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

The compiler says error CS8421: A static local function cannot contain a reference to 'unitPrice'.. The fix is to pass what it needs as a parameter: static int Multiply(int q, int price) => q * price;. That version is easier to reason about and to move out into a normal method later.

C# static local functions take what they need

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

Make local functions static by default and drop the keyword only when you deliberately want to share variables. Many analyzers flag non-static local functions that don't capture anything, because static documents (and enforces) the independence.

Recursion in local functions

Recursion, a function calling itself, is the natural way to walk trees and split problems in halves. A local function can call itself by name, so the recursive helper can live inside the public method and borrow its parameters, which avoids an extra "internal" public method:

C# Recursive local functions

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

Compare this to a lambda: to make a lambda recursive you must first declare the delegate variable and then assign it (Func<int, int>? fact = null; fact = n => n <= 1 ? 1 : n * fact!(n - 1);), because a lambda cannot refer to its own name before the declaration finishes. A local function has none of that friction.

Two cautions: every recursive call uses stack space, and very deep recursion ends in a StackOverflowException that cannot be caught. Recursion covers depth limits, memoization and converting recursion to loops.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. What does public double Area => Width * Height; (in a class) do?

    A property with => is a getter with an expression body. There is no backing field, so the expression runs on every read.
  2. 2. Which line is a valid use of a throw expression?

    throw is allowed as an expression on the right of ??, in a conditional ?: branch, and as an expression-bodied member. Plain assignment of a throw is not meaningful.
  3. 3. What is the effect of marking a local function static?

    A static local function may only use its own parameters and members it can reach statically. The compiler enforces that (error CS8421 if you try to capture).
  4. 4. Why is a local iterator function useful for argument validation?

    Code in an iterator method does not run until enumeration starts. Putting the checks in a normal outer method means errors surface at the call site.
  5. 5. Why can a local function be recursive more easily than a lambda?

    A local function can simply call itself. A lambda has no name; it needs a separately declared delegate variable that is assigned afterwards.

Summary

  • => turns a method, property, accessor, constructor, indexer or operator with one expression into a one-line member. throw may appear as an expression in ??, ?: and => bodies.
  • A => property recomputes on every read; an auto-property with an initializer computes once.
  • A local function is a method declared inside another member; it is visible only there and can be used before its declaration.
  • Local functions can capture the enclosing method's variables (closures). Captured variables are shared, not copied.
  • static local functions cannot capture (error CS8421); pass what they need as parameters. Prefer static unless you need sharing.
  • Local functions are ideal for helper logic, eager validation of iterators and recursion that needs the outer method's data.

Next: Recursion