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 is only relevant to that specific block, improving readability and preventing pollution of the class namespace.
snippet.cs
csharp
1
2
3
4
5
6
7
8
9
10
11
12
public void ProcessTransactions(decimal[] amounts){foreach (var amount in amounts){if (IsValid(amount)){Console.WriteLine($"Processing: {amount}");}}bool IsValid(decimal val) => val > 0 && val < 1000000;}
Breakdown
1
bool IsValid(decimal val) => val > 0 && val < 1000000;
Defines a local function using expression-bodied syntax that is only accessible within ProcessTransactions.
2
if (IsValid(amount))
Calls the local function to perform validation before processing the data.