Local Functions - C# Tutorial
C# Course / Version Features / Local Functions

Local Functions

BLUF: Mastering Local Functions is essential for building robust applications with the .NET ecosystem. This tutorial provides clear explanations and practical examples to help you understand and apply this C# concept.
Enterprise Development Tip: Local Functions

C# is a powerful, modern language for enterprise solutions. Discover how Local Functions enhances your development workflow in the guide below.

C# local functions are private methods of the same type as the one in which they are declared. These functions can only be invoked from within the member that contains them.

Local functions are employed to enhance code clarity and readability.

We can declare local function in the following scope.

  • Methods
  • Constructors
  • Property accessors
  • Event accessors
  • Anonymous methods
  • Lambda expressions
  • Finalizers
  • Other local functions

A local function is a function defined within another function, and it follows the syntax below.

C# Local Function Syntax

Example

<modifiers: async | unsafe> <return-type> <method-name> <parameter-list>

Local functions do not permit the use of access modifiers, not even 'private'. Local variables' members are implicitly private.

Let's see an example.

C# Local Function Example

Example

using System;
namespace CSharpFeatures
{
    public class LocalMethodExample
    {
        public static void Main(string[] args)
        {
            int result = add(10, 20); // calling local method
            Console.WriteLine("sum of 10 and 20 is: " + result);
            // Creating local method
            int add(int a, int b)
            {
                return a + b;
            }
        }
    }
}

Output:

Output

sum of 10 and 20 is: 30

Input Required

This code uses input(). Please provide values below:

Logic Practice
Install Logic Practice
Add to home screen for a faster app-like experience