Local Functions
C# 7.0 introduced the ability to declare functions within methods. In other words, rather than always declaring a method within a class, the method (technically a function) could be declared within another method (see Listing 5.7).
Listing 5.7: Declaring a Local Function
public static void Main() { string GetUserInput(string prompt) { string? input; do { Console.Write(prompt + ": "); input = Console.ReadLine(); } while(string.IsNullOrWhiteSpace(input)); return input!; }; string firstName = GetUserInput("First Name"); string lastName = GetUserInput("Last Name"); string email = GetUserInput("Email Address"); Console.WriteLine($"{firstName} {lastName} <{email}>"); //...
This language construct is called a local function. The reason to declare it like this is that the function’s scope is limited to invocation from within the method where it is declared. Outside of the method’s scope, it is not possible to call the local function. In addition, the local function can access local variables in the method that are declared before the local function. Alternatively, this can explicitly be prevented by adding the static to the beginning of the local function declaration (see “Static Anonymous Functions” (https://essentialcsharp.com/outer-variables) in Chapter 13).