Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

c#
7.0

What are local functions in c# 7.0?

Rukhshan Haroon

In C# 7.0, local functions allow programmers to define a new 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 local function can only be called inside its outer function.

Syntax

<return-type> <method-name> <parameter-list>

Semantics

The semantics of a local function is a little different than that of regular functions.

A local function does not support overloading, and the static keyword 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 local function as members of a local function are private by default.

Advantages

The advantages of local functions are manyfold:

  • 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 local function supports the async and unsafe modifiers.
  • C# 7.0 allows us to define multiple local functions in the body of one function.
  • A local function is able to access the variables declared in the outer function, as well as its parameters.

Example

The following program declares a local function in the body of a pre-existing function, which prints the values of the variables declared in the outer function, as well as 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()
    {
		//variables declared inside the outer function
        int a=5;
        int b=50;
        
        void print_variables(int c, int d)
        {
			//printing variables declared inside the outer function
            Console.WriteLine("Value of a is: " + a);
            Console.WriteLine("Value of b is: " + b);
			//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 5
Value of b is 50
Value of c is 20
Value of d is 40

RELATED TAGS

c#
7.0

CONTRIBUTOR

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

View all Courses

Keep Exploring