About
In this code snippet, we’ll take a look at local functions in C#.
Local functions can be declared and used only within another function. This can be useful for organizing your code. For example, if a function gets too long, you would usually break it up into smaller ones, which will fragment your code. This is the perfect case for using local functions to logically group/contain these smaller functions within the parent function.
Let’s see how to use local functions in the code example below.
Code:
using System; namespace LocalFunctions { internal class Program { static void Main(string[] args) { printNumbers(); } static void printNumbers() { //Calling local_getNumbers() defined and only available within printNumbers(). string numbers = local_getNumbers(); Console.WriteLine(numbers); //Local function string local_getNumbers() { string numbers = string.Empty; for (int i = 0; i < 10; i++) { numbers += i + ", "; } return numbers; } } } }