Skip to content

C# methods, lambdas and extensions

This page covers the features that shape how behavior is declared and called in C#: how short a member can be, where a helper method should live, how values come back through out parameters, how to name symbols without magic strings, how flexible a parameter list can be, how lambdas take ref and out parameters, and how to add members to types you do not own, from classic extension methods to C# 14 extension blocks and C# 15 extension indexers. It closes with default interface methods, which add behavior to an interface itself.

Every sample uses the same invented order-management app, OrdersPortal. Unless a section says otherwise, each sample is a complete file-based app: save it as sample.cs and run dotnet run sample.cs with the .NET 10 SDK (C# 14). The outputs shown were produced with .NET SDK 10.0.115. The extension indexer sample needs the .NET 11 SDK (C# 15) and is marked “not compiled here”.

Feature Version Use it when
Expression-bodied members C# 6, more member kinds in C# 7.0 A member is a single expression.
Local functions C# 7.0 A helper is used by only one method.
Static local functions C# 8 That helper must not capture locals or this.
Out variables C# 7.0 Calling a TryXxx method.
nameof C# 6 A string must match a parameter, member or type name.
nameof with unbound generic types C# 14 You need the name of a generic type definition such as List<>.
Params collections C# 13 A variable-argument API should avoid array allocations or accept any collection.
Lambda parameter modifiers C# 14 A lambda needs ref, out, in or scoped without spelling out every type.
Extension methods C# 3 Adding a method to a type you cannot change.
Extension members C# 14 Adding properties, static members or operators, or grouping extensions by receiver.
Extension indexers C# 15 Adding [] access to a type you cannot change.
Default interface methods C# 8 Evolving a published interface without breaking implementers.

Introduced in C# 6 (methods, operators, read-only properties and indexers) and extended in C# 7.0 (constructors, finalizers, and get, set and init accessors). An expression body replaces a block that contains a single return or a single statement expression with => expression. The compiled code is identical; the benefit is that small members read as definitions rather than procedures, and a class full of one-line members becomes easy to scan. A get-only property written as public decimal Total => _lines.Sum(); is evaluated on every read, which is different from public decimal Total { get; } = _lines.Sum();, which is evaluated once.

var cart = new Cart("ORD-5001");
cart.Add(2, 12.50m);
cart.Add(1, 4.99m);
Console.WriteLine(cart);
Console.WriteLine($"First line: {cart[0]}");
public sealed class Cart
{
private readonly List<decimal> _lines = [];
public Cart(string orderId) => OrderId = orderId; // constructor (C# 7.0)
public string OrderId { get; }
public decimal Total => _lines.Sum(); // read-only property (C# 6)
public decimal this[int index] => _lines[index]; // indexer (C# 6)
public void Add(int quantity, decimal unitPrice) => _lines.Add(quantity * unitPrice); // method (C# 6)
public override string ToString() => $"{OrderId}: {_lines.Count} lines, {Total:0.00}";
}

Output:

ORD-5001: 2 lines, 29.99
First line: 25.00

Pitfalls:

  • => expr and { get; } = expr look similar but mean “computed every time” versus “computed once”. Mixing them up causes stale values or repeated expensive work.
  • Long ternary chains squeezed into one expression are harder to debug than a block body; use a block once there are branches.

Introduced in C# 7.0 (Visual Studio 2017). A local function is a named method declared inside another member. It can read the enclosing method’s parameters and locals, call itself recursively, be generic, be an iterator or async, and be called before the line that declares it. Compared with a lambda assigned to a variable, a local function has no delegate allocation unless you convert it to a delegate, and captured variables are passed in a struct instead of a heap closure. Its best-known use is splitting an iterator or async method so argument validation runs immediately instead of on the first MoveNext() or await.

try
{
var batches = Batch(["ORD-1", "ORD-2", "ORD-3", "ORD-4", "ORD-5"], size: 2);
foreach (var batch in batches)
Console.WriteLine(string.Join(", ", batch));
Batch(["ORD-6"], size: 0); // throws here, not on first MoveNext()
}
catch (ArgumentOutOfRangeException ex)
{
Console.WriteLine($"Rejected: {ex.ParamName}");
}
static IEnumerable<string[]> Batch(IReadOnlyList<string> orderIds, int size)
{
ArgumentOutOfRangeException.ThrowIfLessThan(size, 1); // runs eagerly
return Iterate();
// The iterator body is a local function, so validation is not deferred.
IEnumerable<string[]> Iterate()
{
for (int i = 0; i < orderIds.Count; i += size)
yield return orderIds.Skip(i).Take(size).ToArray();
}
}

Output:

ORD-1, ORD-2
ORD-3, ORD-4
ORD-5
Rejected: size

Pitfalls:

  • Capturing a local that later changes means the local function sees the new value; capture is by reference, not by snapshot.
  • If several methods need the helper, make it a private method; a local function cannot be unit tested or reused on its own.

Introduced in C# 8 (.NET Core 3.0). Adding static to a local function forbids it from capturing locals, parameters or this from the enclosing scope. Everything it needs must arrive through its own parameters, which makes data flow explicit and guarantees there is no hidden closure state. The compiler reports error CS8421 if the body touches an outer variable. C# 9 allowed the same static modifier on lambdas. In top-level programs, marking helpers static also prevents them from quietly reading top-level locals.

decimal taxRate = 0.2m;
decimal[] subtotals = [100m, 250m];
foreach (var subtotal in subtotals)
Console.WriteLine(WithTax(subtotal, taxRate));
// static: cannot read taxRate (or this) from the enclosing scope by accident.
// Writing "value * (1 + taxRate)" without the parameter is error CS8421.
static decimal WithTax(decimal value, decimal rate) => decimal.Round(value * (1 + rate), 2);

Output:

120.0
300.0

Pitfalls:

  • static prevents capture, not side effects: the function can still mutate objects passed in or call static state.
  • Default to static for local helpers and remove it only when capture is intended; the reverse habit lets accidental captures slip in.

Introduced in C# 7.0. You can declare the variable that receives an out argument at the call site: dictionary.TryGetValue(key, out var price). The declaration can use var or an explicit type, and you can replace it with a discard (out _) when only the return value matters. This removes the separate, uninitialized declaration line that the Try pattern used to require, and it keeps the variable next to the code that fills it. Out variables are also allowed in field initializers, constructor initializers and query clauses since C# 7.3.

var prices = new Dictionary<string, decimal> { ["SKU-1"] = 9.99m, ["SKU-2"] = 24.00m };
string[] requested = ["SKU-2", "SKU-9"];
foreach (var sku in requested)
{
if (prices.TryGetValue(sku, out var price))
Console.WriteLine($"{sku}: {price}");
else
Console.WriteLine($"{sku}: not found");
}
if (!int.TryParse("15", out int quantity))
quantity = 1;
Console.WriteLine($"Quantity in scope after the if: {quantity}");

Output:

SKU-2: 24.00
SKU-9: not found
Quantity in scope after the if: 15

Pitfalls:

  • An out variable declared in an if condition is in scope for the rest of the enclosing block, not only inside the if. That is useful for the guard pattern above but surprising when names clash.
  • When TryXxx returns false, the out value is the default (0, null), not “unchanged”. Do not read it on the failure path unless you reassign it.

Introduced in C# 6. nameof(x) is a compile-time constant string containing the simple name of a variable, parameter, member, type or namespace. Because the compiler checks the symbol, renaming it in the IDE updates the string too, which magic strings never do. Typical uses are exception parameter names, INotifyPropertyChanged notifications, log messages, route or configuration keys, and attribute arguments such as [NotNullIfNotNull(nameof(input))]. For ArgumentNullException and friends, prefer the ThrowIfNull helpers in .NET 6 and later, which capture the argument expression automatically.

var order = new Order { Id = "ORD-6001", Total = -5m };
try
{
Validate(order);
}
catch (ArgumentOutOfRangeException ex)
{
Console.WriteLine(ex.Message);
}
Console.WriteLine(nameof(Order.Total)); // just the member name
Console.WriteLine(nameof(System.Collections.Generic.List<int>));
Console.WriteLine(nameof(Validate));
static void Validate(Order order)
{
ArgumentNullException.ThrowIfNull(order);
if (order.Total < 0)
throw new ArgumentOutOfRangeException(nameof(order), $"{nameof(Order.Total)} must not be negative.");
}
public sealed class Order
{
public required string Id { get; init; }
public decimal Total { get; init; }
}

Output:

Total must not be negative. (Parameter 'order')
Total
List
Validate

Pitfalls:

  • nameof returns only the last identifier: nameof(Order.Total) is Total, and nameof(System.Collections.Generic.List<int>) is List. Use typeof(T).FullName when you need the qualified name.
  • It is a compile-time name, not a runtime value; it cannot be applied to a dynamic member (CS8364).

Introduced in C# 14 (.NET 10, November 2025). Before C# 14, nameof accepted a generic type only in closed form, so getting the name List meant writing a placeholder argument such as nameof(List<int>). Now the argument can be an unbound generic type such as List<>, Dictionary<,> or your own Repository<>, and you can reach members through it: nameof(Repository<>.FindAsync). This reads better in analyzers, source generators, diagnostics and DI registration code where the generic type definition, not a particular construction, is the subject.

Console.WriteLine(nameof(List<>));
Console.WriteLine(nameof(Dictionary<,>));
Console.WriteLine(nameof(Repository<>));
Console.WriteLine(nameof(Repository<>.FindAsync)); // members of an unbound type work too
Console.WriteLine(typeof(Repository<>).Name); // runtime name differs
public sealed class Repository<TEntity>
{
public Task<TEntity?> FindAsync(string id) => Task.FromResult<TEntity?>(default);
}

Output:

List
Dictionary
Repository
FindAsync
Repository`1

Pitfalls:

  • nameof(List<>) is List, not List<> and not the metadata name List`1. Use typeof(List<>).Name when you need the arity suffix.
  • The project must compile with C# 14 or later (the default for net10.0); older language versions report an error.

Introduced in C# 13 (.NET 9). Before C# 13, a params parameter had to be an array, so every call allocated one. Now params can be any type that a collection expression can create: Span<T>, ReadOnlySpan<T>, IEnumerable<T>, IReadOnlyList<T>, IList<T> and related interfaces, or a type with a collection builder or an Add method. Callers still write a comma-separated list, and the compiler can place a ReadOnlySpan<T> argument on the stack. Many .NET 9 methods, such as string.Join and Task.WhenAll, gained span overloads for this reason, so recompiling against .NET 9 or later can remove allocations without code changes.

Log("info", "payments", "approved"); // no array allocated
Log(); // empty span
Log(["warn", "inventory", "low stock"]); // collection expression also works
Console.WriteLine(Sum(10m, 20m, 5.5m));
Console.WriteLine(Sum(new List<decimal> { 1m, 2m })); // any IEnumerable<decimal>
static void Log(params ReadOnlySpan<string> parts)
=> Console.WriteLine(parts.IsEmpty ? "(nothing to log)" : string.Join(" | ", parts.ToArray()));
static decimal Sum(params IEnumerable<decimal> amounts) => amounts.Sum();

Output:

info | payments | approved
(nothing to log)
warn | inventory | low stock
35.5
3

Pitfalls:

  • A params ReadOnlySpan<T> parameter cannot be captured by a lambda, stored in a field or used across await; it is a ref struct.
  • Adding a span overload next to an existing params T[] overload changes which method existing callers bind to when they recompile. Check overload resolution before shipping such a change in a library.

Introduced in C# 14 (.NET 10). A lambda can now put ref, out, in, ref readonly or scoped on its parameters while still letting the compiler infer their types from the target delegate: (text, out result) => decimal.TryParse(text, out result). Before C# 14, using any modifier forced you to write the type of every parameter, (string text, out decimal result) => ..., which made Try-pattern and span-based delegates noisy. Only the modifiers are new; the delegate type still decides the parameter types.

TryParse<decimal> parsePrice = (text, out result) => decimal.TryParse(text, out result);
Adjust<decimal> addShipping = (ref total) => total += 4.95m;
foreach (var raw in new[] { "19.99", "abc" })
{
if (parsePrice(raw, out var price))
{
addShipping(ref price);
Console.WriteLine($"{raw} -> {price}");
}
else
{
Console.WriteLine($"{raw} -> invalid");
}
}
delegate bool TryParse<T>(string text, out T result);
delegate void Adjust<T>(ref T value);

Output:

19.99 -> 24.94
abc -> invalid

Pitfalls:

  • params is the exception: a lambda with a params parameter still needs an explicitly typed parameter list.
  • The lambda needs a target delegate type; var parse = (text, out result) => ... cannot infer anything.

Introduced in C# 3 (.NET Framework 3.5), the feature that made LINQ possible. An extension method is a static method in a static, non-nested, non-generic class whose first parameter has the this modifier. When its namespace is imported, it can be called with instance syntax on the receiver type: order.IsOverdue(today). The compiler simply rewrites the call to OrderExtensions.IsOverdue(order, today). Extension methods suit helpers on types you cannot modify (framework types, interfaces, generated code) and fluent APIs over interfaces, where every implementation gets the method for free.

using OrdersPortal.Extensions;
var order = new Order("ORD-7001", new DateOnly(2026, 11, 1));
var today = new DateOnly(2026, 11, 18);
Console.WriteLine(order.IsOverdue(today, graceDays: 14));
Console.WriteLine(OrderExtensions.IsOverdue(order, today, graceDays: 30)); // what the compiler emits
public sealed record Order(string Id, DateOnly DueDate);
namespace OrdersPortal.Extensions
{
public static class OrderExtensions
{
public static bool IsOverdue(this Order order, DateOnly today, int graceDays = 0)
=> today > order.DueDate.AddDays(graceDays);
}
}

Output:

True
False

Pitfalls:

  • An instance method with the same signature always wins, so an extension can be silently shadowed when the type later adds that method.
  • Extensions are bound statically. They cannot be overridden or mocked, and they see only the public surface of the receiver.
  • Broad extensions on object or string pollute IntelliSense for the whole codebase; keep them in narrowly named namespaces.

Introduced in C# 14 (.NET 10). An extension block inside a static class declares a receiver once and then any number of members for it: methods, properties, and, with a receiver type but no receiver name, static members and user-defined operators that appear to belong to the type itself (Order.Empty(...)). Extension properties were the most requested missing piece. Existing this-parameter extension methods keep working and are source and binary compatible, so you can convert a class one member at a time.

using OrdersPortal.Extensions;
var order = new Order("ORD-7002", [19.99m, 5.01m, 0m]);
Console.WriteLine(order.Total); // extension property
Console.WriteLine(order.HasFreeItems); // extension property
Console.WriteLine(order.WithLine(10m).Total); // extension method
Console.WriteLine(Order.Empty("ORD-7003").Total); // static extension member on the type
public sealed record Order(string Id, IReadOnlyList<decimal> Lines);
namespace OrdersPortal.Extensions
{
public static class OrderExtensions
{
extension(Order order) // instance extension members
{
public decimal Total => order.Lines.Sum();
public bool HasFreeItems => order.Lines.Any(l => l == 0m);
public Order WithLine(decimal amount) => order with { Lines = [.. order.Lines, amount] };
}
extension(Order) // static extension members
{
public static Order Empty(string id) => new(id, []);
}
}
}

Output:

25.00
True
35.00
0

Pitfalls:

  • Extension properties cannot have state: there is no backing field, so a “property” that needs storage still belongs on the type (or in a ConditionalWeakTable).
  • Like extension methods, extension members never override real members of the receiver and are only visible when their namespace is imported.

Introduced in C# 15 (.NET 11, November 2026); not a preview feature. C# 14 extension blocks could add methods, properties and operators but not indexers. C# 15 closes that gap: an extension block can declare this[...], so receiver[index] works on a type that does not define that indexer. Because indexers are always instance members, the extension block must name its receiver parameter. Typical uses are natural lookup syntax on interfaces and third-party types, or on domain wrappers where catalog["SKU-1"] reads better than a method call.

Not compiled here (needs .NET 11 SDK); syntax verified against the Microsoft Learn C# 15 documentation.

using OrdersPortal.Extensions;
IEnumerable<Order> recent = [new("ORD-9001", 120m), new("ORD-9002", 45m)];
Console.WriteLine(recent["ORD-9002"]?.Total); // extension indexer on IEnumerable<Order>
public sealed record Order(string Id, decimal Total);
namespace OrdersPortal.Extensions
{
public static class OrderListExtensions
{
extension(IEnumerable<Order> orders)
{
public Order? this[string id] => orders.FirstOrDefault(o => o.Id == id);
}
}
}

Expected output:

45

Pitfalls:

  • If the receiver type already has an applicable indexer, the type’s own indexer wins.
  • [] suggests a cheap lookup. Hiding a linear search or ElementAt on a lazy sequence behind it can surprise callers.

Introduced in C# 8 (.NET Core 3.0). An interface member can have a body. Classes that implement the interface inherit that body unless they provide their own, so a library can add a member to a published interface without breaking every implementer. The feature needs runtime support, so it is unavailable on .NET Framework and .NET Standard 2.0 targets. It also brought private, protected, static and virtual members to interfaces, and later C# 11 static abstract members.

IOrderNotifier notifier = new EmailNotifier();
notifier.Notify("ORD-8001", "shipped");
notifier.NotifyFailure("ORD-8002", "card declined"); // default implementation
var concrete = new EmailNotifier();
// concrete.NotifyFailure(...) does not compile: default members are only reachable through the interface.
((IOrderNotifier)concrete).NotifyFailure("ORD-8003", "address invalid");
public interface IOrderNotifier
{
void Notify(string orderId, string message);
// Added in a later version of the interface without breaking existing implementers.
void NotifyFailure(string orderId, string reason) => Notify(orderId, $"FAILED: {reason}");
}
public sealed class EmailNotifier : IOrderNotifier
{
public void Notify(string orderId, string message) => Console.WriteLine($"email {orderId}: {message}");
}

Output:

email ORD-8001: shipped
email ORD-8002: FAILED: card declined
email ORD-8003: FAILED: address invalid

Pitfalls:

  • Default members are not inherited by the class: calling them on a variable of the class type is error CS1061.
  • Interfaces still cannot hold instance state, so defaults can only be built from other interface members.
  • If two interfaces supply defaults for the same member, the class must implement it to resolve the diamond.
  • Helper for one method: a static local function. Helper for several methods: a private method. Logic passed as data: a lambda.
  • Behavior on a type you own: an instance member. Behavior on a type you do not own: an extension method, or an extension block when you need properties, static members or several members on one receiver.
  • New member on a published interface: a default interface method if all target runtimes support it; otherwise an extension method on the interface.
  • Variable arguments in a hot path: params ReadOnlySpan<T>. Variable arguments that must be stored: params IEnumerable<T> or an array.

What is the difference between a local function and a lambda stored in a local variable? A local function is a real method: it can be generic, recursive, an iterator, and used before its declaration. A lambda is converted to a delegate (an allocation) and its captured variables live in a heap closure. A local function captures through a struct when it is not converted to a delegate, so it is usually cheaper.

Why do iterator and async methods often split into an outer method and a local function? Code in an iterator does not run until the first MoveNext(), and an async method reports exceptions through its task. Putting validation in a non-iterator outer method and the yield body in a local function makes argument errors throw at the call site.

Can an extension method override an instance method? No. Instance members always win in overload resolution, and extensions are bound statically, so they cannot be virtual. If a type later adds a member with the same signature, callers silently switch to it when they recompile.

What do C# 14 extension members add over extension methods? Extension properties, static extension members and operators that appear on the type itself, and grouping of several members under one receiver declaration. C# 15 adds extension indexers. The old syntax still works and compiles to compatible metadata.

Senior scenario: OrdersPortal publishes an IPaymentGateway NuGet interface used by twenty partner implementations. You need a RefundPartialAsync method. How do you add it? Adding an abstract member breaks every partner at compile time and their already-built assemblies at run time. Options: a default interface method that throws NotSupportedException or composes existing members (only if every consumer runs on .NET Core 3.0 or later); a new IPartialRefundGateway interface that partners opt into, detected with a type test; or an extension method if the operation can be built from existing members. Prefer the opt-in interface when the behavior cannot be implemented generically, and document the default’s behavior if you use one.