Local functions are private functions of a type that are nested in another member. They can only be called from their containing member. It can be declared in and called from the following

1. Constructors
2. iterator methods
3. async methods
4. Events
5. Properties
6. Anonymous functions
7. Lambda expressions

Local function is the new features introduced in C# 7.

Local function will helps in performance of the logic in the form of reducing the copy of data between memory locations. It will reduce the use of scope but this allows the use of variables declared in there enclosing scope without assigning additional memory on there heap or stack memory.

If any other developers review our Local function declaration its very easy to understand and clearly readable.

Example for Local Function :

using System;					
public class Program
{
	public static void Main()
	{
		sum(5);
		sum(5,5); //Passing multiple parameters using prams keyword
		sum(5,5,5); //Passing multiple parameters using prams keyword
		
                //Local Function
		void sum(params int[] array1){
			int num=0;
			foreach(var i in array1){
				num=num+i;
			}
			Console.WriteLine("The Sum of  results: {0}", num);		
		}		
		
	}
}

By admin

Leave a Reply

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