Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags


What are static local functions in c# 8.0?

Rukhshan Haroon

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:

  • Local functions make the code more readable and prevent function calls by mistake, as a local function may only be called inside its outer function.
  • A static local function supports the async and unsafe modifiers.
  • C# 8.0 allows us to define multiple static local functions in the body of one function.


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 function
    public static void Main()
        //declaration of local function
        static void print_variables(int c, int d)
			//printing variables passed as parameters to the local function
            Console.WriteLine("Value of a is: " + c);
            Console.WriteLine("Value of b is: " + d);
        // Inner or local function called
        print_variables(20, 40);

The output of this program is as follows:

Value of a is: 20
Value of b is: 40




Rukhshan Haroon
Copyright ©2022 Educative, Inc. All rights reserved

View all Courses

Keep Exploring