In C# 8.0, static local functions allow programmers to define a new, static function inside the body of a pre-existing function. The scope of the inner function is local to the outer function used to create it.
A static local function is different from a local function, as it cannot reference a variable declared outside of it. It can only access variables declared inside its body or passed to it as parameters.
A static local function can only be called inside its outer function.
Local functions were originally introduced in C# 7.0, but only C# 8.0 supports static local functions.
static <return-type> <method-name> <parameter-list>
The semantics of a static local function is a little different than that of regular functions.
A static local function does not support overloading, and attributes cannot be applied to its parameters or parameter type.
Similarly, member access modifiers, such as the keyword private, must not be used inside the body of a static local function as members of a static local function are private by default.
The advantages of static local functions are manifold:
async and unsafe modifiers.The following program declares a static local function in the body of a pre-existing function, which prints the values of the variables passed to it as parameters.
Values of variables are printed using the Console.WriteLine function.
using System;public class Program {// Main functionpublic static void Main(){//declaration of local functionstatic void print_variables(int c, int d){//printing variables passed as parameters to the local functionConsole.WriteLine("Value of a is: " + c);Console.WriteLine("Value of b is: " + d);}// Inner or local function calledprint_variables(20, 40);}}
The output of this program is as follows:
Value of a is: 20
Value of b is: 40
Free Resources