csharp / intermediate
Snippet
Encapsulating Logic with Static Local Functions
Local functions allow you to define methods inside other methods. Marking them as static prevents them from capturing variables from the outer scope, which reduces memory allocation and improves performance.
snippet.cs
csharp
1
2
3
4
5
6
public int CalculateSequence(int start, int limit){return Step(start);static int Step(int n) => n > 100 ? n : Step(n * 2);}
Breakdown
1
static int Step(int n)
Defines a local function that cannot access local variables from CalculateSequence.
2
=> n > 100 ? n : Step(n * 2)
A recursive expression body that continues the sequence until the limit is reached.