csharp / intermediate
Snippet
Scoped Utility Logic with Local Functions
Local functions allow you to define helper methods inside another method scope. Using the 'static' modifier ensures the local function cannot capture variables from the enclosing scope, reducing memory pressure and unintended side effects.
snippet.cs
csharp
1
2
3
4
5
6
7
8
9
public void ProcessData(IEnumerable<int> data){static int Square(int x) => x * x;foreach (var item in data){Console.WriteLine(Square(item));}}
Breakdown
1
static int Square(int x)
Declares a static local function that only has access to its parameters.
2
Square(item)
Invokes the local helper within the method scope.