C# Local Functions

Code Snippets Local Functions
Share:

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;
            }
        }
    }
}

Resulting output:

Share:

Leave a Reply

Your email address will not be published. Required fields are marked *

The following GDPR rules must be read and accepted:
This form collects your name, email and content so that we can keep track of the comments placed on the website. For more info check our privacy policy where you will get more info on where, how and why we store your data.

Advertisment ad adsense adlogger