CHASH Tutorial



C# LOCAL FUNCTIONS


C# Local Functions

Local functions are functions defined inside another method. They help organize code by keeping helper functions close to where they are used, improving readability and encapsulation.

Features

  • Defined inside a method (like Main or any other method).
  • Can access variables from the enclosing method.
  • Not accessible outside the containing method.

Example: Using a Local Function

class Program
{
    static void Main()
    {
        Console.WriteLine("Factorial of 5 is: " + Factorial(5));

        // Local function to calculate factorial
        int Factorial(int n)
        {
            if (n <= 1)
                return 1;
            return n * Factorial(n - 1);
        }
    }
}
  

Why Use Local Functions?

  • Encapsulate helper logic inside methods without cluttering class scope.
  • Access variables from the outer method easily.
  • Improve code readability and maintenance.

🌟 Enjoyed Learning with Us?

Help others discover Technorank Learning by sharing your honest experience.
Your support inspires us to keep building!

Leave a Google Review