csharp / intermediate
Snippet
Encapsulating Logic with Local Functions
Local functions allow you to define methods inside the scope of another method. This is useful for helper logic that should not be accessible by other members of the class, promoting cleaner encapsulation and reducing class-level clutter.
snippet.cs
csharp
1
2
3
4
5
6
7
8
9
10
11
12
public void ProcessData(IEnumerable<string> items){bool IsValid(string item) => !string.IsNullOrWhiteSpace(item) && item.Length > 3;foreach (var item in items){if (IsValid(item)){Console.WriteLine($"Processing: {item.Trim()}");}}}
Breakdown
1
bool IsValid(string item) => ...
Declares a local function that is only visible within the ProcessData method.
2
if (IsValid(item))
Calls the local function to perform validation before processing the item.