Search⌘ K
AI Features

Local Functions

Explore the concept of local functions in C# to improve code readability and structure. Learn how to define private helper methods within other methods, manage scope effectively, and use static local functions to avoid unwanted memory usage. This lesson helps you write cleaner, more maintainable code in your .NET projects.

C# allows us to define private methods, known as local functions, within other methods.

A method that contains other methods
A method that contains other methods

Local functions improve code readability by keeping helper logic close to where it is used. If a method is only called by one specific parent method, making it local prevents accidental calls from other parts of the class.

Defining a local function

We define local functions like regular methods, but we nest them inside an existing method body.

C# 14.0
Print("Hello World!");
void Print(string textToPrint)
{
int times = 4;
// We define a local function inside Print
// It cannot have an access modifier like public or private
void PrintTimes()
{
// Local functions can access variables from the enclosing method
// This is called "capturing"
for (int i = 0; i < times; i++)
{
Console.WriteLine(textToPrint);
}
}
// We call the local function
PrintTimes();
}
    ...