DEV Community

Juarez Júnior
Juarez Júnior

Posted on

C# Tip: Local Functions

Let’s explore Local Functions, introduced in C# 7, which allow you to define functions within methods to better organize your code and encapsulate specific logic. See the example in the code below.

using System;

public class Program
{
    public static void Main()
    {
        int number = 5;
        Console.WriteLine($"Factorial of {number} is {CalculateFactorial(number)}");

        // Local function to calculate factorial
        int CalculateFactorial(int n)
        {
            if (n <= 1) return 1;
            return n * CalculateFactorial(n - 1);
        }
    }
}
Enter fullscreen mode Exit fullscreen mode

Explanation:
With Local Functions, you can create functions inside methods that are only visible within that scope. This helps keep your code more organized, especially when you have logic that is only used within a single method and doesn’t need to be exposed globally. In the example above, a local function is used to calculate the factorial of a number, encapsulating the logic within the main method.

Source code: GitHub

I hope this tip helps you use Local Functions to keep your code cleaner and more organized! Until next time.

Top comments (0)