[C#] Hiding Helper Methods within Scope Using Local Functions

Introduced in C# 7.0, Local Functions allow you to define a function directly inside another method.

Previously, even small helper methods used only by a specific method had to be defined as private methods of the class. This often cluttered the class and reduced overall readability. By using local functions, you can place logic “immediately close to where it is used,” promoting encapsulation and making the code structure clearer.

In this article, I will explain how to define and use local functions, using a process that converts string arrays to snake_case as an example.

目次

Table of Contents

  1. Implementation Example: Snake Case Conversion
  2. Features and Benefits of Local Functions
  3. Summary

Implementation Example: Snake Case Conversion

The following code is a program that converts a list of words written in PascalCase to snake_case and outputs them. The conversion logic, ToSnakeCase, is defined as a local function because it is used only inside the Main method.

using System;
using System.Linq;

namespace LocalFunctionExample
{
    class Program
    {
        static void Main(string[] args)
        {
            // String array to convert
            var words = new[]
            {
                "StringBuilder",
                "ToSnakeCase",
                "IsLetter",
                "ToLower"
            };

            Console.WriteLine("--- Conversion Results ---");

            foreach (var word in words)
            {
                // Call local function
                var snakeCase = ToSnakeCase(word);
                Console.WriteLine($"{word} -> {snakeCase}");
            }

            // --- Define local function here ---
            
            // Local function to convert PascalCase to snake_case
            // This function is invisible from outside the Main method
            string ToSnakeCase(string value)
            {
                if (string.IsNullOrEmpty(value)) return value;

                // Insert "_" before uppercase letters (except the first one)
                var convertedSequence = value.Select((c, i) => 
                    (i > 0 && char.IsUpper(c)) ? "_" + c : c.ToString()
                );

                // Join strings and convert to lowercase
                return string.Concat(convertedSequence).ToLower();
            }
        }
    }
}

Features and Benefits of Local Functions

1. Limiting Scope (Preventing Pollution)

Local functions can only be called from within the method (parent method) where they are defined. This eliminates the need to search through the entire class to find where a method is used, clarifying code dependencies.

2. Accessing Parent Method Variables (Closure)

Local functions can directly access (capture) variables and arguments defined in the parent method. This saves you the trouble of explicitly passing values as arguments.

void ProcessData(int threshold)
{
    var numbers = new[] { 1, 5, 10, 2 };
    
    // Can directly use the parent method's argument 'threshold'
    var filtered = numbers.Where(IsOverThreshold);
    
    bool IsOverThreshold(int n) => n > threshold;
}

3. Immediate Exception Handling in Iterator or Async Methods

In iterator methods using yield return or async/await methods, a common pattern is to validate arguments (such as null checks) immediately and then delegate the actual processing to a local function. This ensures that errors are detected reliably before the deferred execution begins.


Summary

Local functions are a powerful feature for increasing code cohesion.

  • Usage: When a helper method is referenced only by a specific method.
  • Position: Anywhere within the parent method (commonly at the end of the method or just before use).
  • Effect: Organizes logic without polluting the class-level namespace.

Use local functions not just for code organization, but also to leverage features like variable capturing to write code that clearly conveys your intent.

よかったらシェアしてね!
  • URLをコピーしました!
  • URLをコピーしました!

この記事を書いた人

私が勉強したこと、実践したこと、してることを書いているブログです。
主に資産運用について書いていたのですが、
最近はプログラミングに興味があるので、今はそればっかりです。

目次