1.24 — Partial Classes, Partial Methods, Local Functions¶
← Roadmap · Section: 1. C# Language Fundamentals Prev: 1.23 Attributes and reflection · Next: 1.25 Span and Memory
Markers: — · Confidence: 🔴 · Last reviewed: —
TL;DR¶
partiallets one class be split across several files. It exists mainly so generated code and your code can live in the same class without overwriting each other.- A local function is a method declared inside another method. It is faster than a lambda and can be called before it is declared.
- Prefer a local function over a lambda for a private helper — and mark it
staticif it does not need anything from around it.
The concept¶
Both of these are about organising code, not about new capability.
partial answers: "how do I have both hand-written and machine-generated code in the same
class, without the generator wiping out my work every time it runs?"
Local functions answer: "I need a small helper that only this one method uses — where do I put it so it does not clutter the class?"
How it works¶
Partial classes¶
Add partial to a class and you can split it across as many files as you like. The
compiler joins them back into one class.
// Order.cs — your hand-written code
public partial class Order
{
public void ApplyDiscount(decimal percent) { /* ... */ }
}
// Order.Generated.cs — written by a tool
public partial class Order
{
public Guid Id { get; set; }
public decimal Total { get; set; }
}
At compile time these become one class with all four members. Neither file knows about the other.
Rules: every part needs partial, they must all be in the same assembly and namespace, and
accessibility must match.
Where you will actually meet this:
- Razor Pages — the
.cshtmlfile and its.cshtml.cscode-behind are two halves of one partial class - EF Core scaffolding from an existing database
- Blazor components
- Source generators, which need somewhere to put the code they write
Where not to use it: splitting your own class across files because it got too big. A class that needs three files to hold it is a class doing too much. Splitting it up hides the problem instead of fixing it.
Partial methods¶
A partial method is declared in one part and optionally implemented in another:
public partial class Order
{
public void Complete()
{
Status = OrderStatus.Complete;
OnCompleted(); // a hook
}
partial void OnCompleted(); // declared, maybe never implemented
}
The clever bit: if nobody implements OnCompleted, the compiler removes the call
entirely. There is no empty method call at runtime, no cost at all.
This is how generated code offers extension points. The tool writes the hook; you implement it only if you need it.
Since C# 9, partial methods can also have a return value and be public, but then an
implementation becomes mandatory — the compiler cannot silently remove a call that
produces a value someone is using.
Local functions¶
A method declared inside another method:
public IEnumerable<int> GetFactors(int number)
{
ValidateInput(); // called before it is declared — fine
for (var i = 1; i <= number; i++)
if (number % i == 0)
yield return i;
void ValidateInput() // declared at the bottom
{
if (number <= 0)
throw new ArgumentOutOfRangeException(nameof(number));
}
}
Two things worth noting. You can call it before it is declared, unlike a local variable
— so you can put helpers at the bottom and keep the main logic at the top. And it can see
the enclosing method's parameters and variables, which is why ValidateInput can use
number without it being passed in.
Local function versus lambda¶
| Local function | Lambda | |
|---|---|---|
| Allocates an object? | No, unless it captures | Yes — a delegate, plus a closure if it captures |
| Can be recursive? | Yes, naturally | Awkward |
| Can be called before declaration? | Yes | No |
| Can be passed as an argument? | Yes, converts to a delegate | Yes, that is the point |
Can use yield return? |
Yes | No |
Prefer a local function for a private helper. It is faster (often no allocation at all, because the compiler can make it a plain static method), it reads better, and it supports recursion and iterators.
Use a lambda when you are passing behaviour to something — a LINQ operator, an event handler, a callback parameter.
The static local function¶
Adding static stops the function capturing anything from the enclosing method:
public int Process(int[] data)
{
var multiplier = 3;
return data.Sum(x => Transform(x));
static int Transform(int value) => value * 2;
// 'static' means this CANNOT touch 'multiplier'.
// Try it and the compiler stops you.
}
Why bother? Because capturing allocates a hidden object
(see 1.13). Marking it static guarantees that does not happen,
and turns an accidental capture into a compile error instead of a silent allocation.
It is worth making static your default for local functions and only removing it when
you genuinely need to capture something.
A common real use — separating validation from an iterator¶
This is a genuinely useful pattern that surprises people:
public IEnumerable<Order> GetOrders(Guid customerId)
{
if (customerId == Guid.Empty)
throw new ArgumentException("Invalid id", nameof(customerId));
return Iterate();
IEnumerable<Order> Iterate()
{
foreach (var order in _db.Orders.Where(o => o.CustomerId == customerId))
yield return order;
}
}
Why split it? Because a method containing yield return does not run at all until
someone enumerates it. So if the validation were in the same method, this would happen:
var orders = GetOrders(Guid.Empty); // no exception here!
foreach (var o in orders) { } // exception thrown HERE, far from the cause
Moving the validation into an outer non-iterator method makes it run immediately, so the error appears at the call site where it makes sense. See 2.4.
Interview questions¶
Q: What is a partial class and why does it exist?
It lets one class be split across several files, which the compiler joins back together. Its real purpose is code generation — it allows a tool to own one file while you own another, so regenerating does not overwrite your work. Razor Pages code-behind, EF Core scaffolding, Blazor components and source generators all rely on it. It is not intended as a way to break up a class that has grown too large; if a class needs several files to hold it, the real problem is that the class is doing too much.
Q: What is a partial method?
A method declared in one part of a partial class and optionally implemented in another. If nobody implements it, the compiler removes both the declaration and every call to it, so it costs nothing at runtime. That makes it a zero-cost extension point for generated code — the generator writes a hook, and you implement it only if you need to. Since C# 9 they can return values and be public, but then an implementation is required, because the compiler cannot delete a call whose result is being used.
Q: When would you use a local function instead of a lambda?
For a private helper used only inside one method. A local function is usually cheaper —
if it does not capture anything the compiler can emit it as a plain static method with no
allocation at all, whereas a lambda always allocates a delegate. It can also be recursive
naturally, it can use yield return, and it can be called before it is declared, so you
can keep helpers at the bottom of the method. I would use a lambda when I am passing
behaviour to something else, like a LINQ operator.
Q: What does static on a local function do?
It prevents the function from capturing variables from the enclosing method. That guarantees no closure object is allocated, and it makes an accidental capture a compile error rather than a silent performance cost. It also documents that the function depends only on its own parameters. It is a good default.
Traps ⚠️¶
- Using
partialto hide an oversized class. Splitting it across files makes it harder to see the problem, not easier. - A partial method with no implementation is silently removed. Convenient by design, confusing if you did not know and are wondering why your hook never fires.
- All parts must be in the same assembly and namespace. You cannot split a class across projects.
- Local functions capture just like lambdas. They are not automatically free — mark
them
staticif you want that guaranteed. - A method containing
yield returndoes not execute until enumerated. Argument validation in such a method is delayed. Split it into an outer method plus a local iterator function. - Local functions cannot be
async void, which is a good thing.
Related¶
- 1.5 static — static local functions
- 1.13 Lambdas and closures — what capturing costs
- 2.4 yield and iterators — the deferred-validation problem
- 1.23 Attributes and reflection — source generators use partial classes
- 21.13 Source generators — the main modern use of
partial