What are Local functions in C# 7.0?

CsharpServer Side ProgrammingProgramming

Local functions are private methods of a type that are nested in another member. They can only be called from their containing member.

Local functions can be declared in and called from −

  • Methods, especially iterator methods and async methods

  • Constructors

  • Property accessors

  • Event accessors

  • Anonymous methods

  • Lambda expressions

  • Finalizers

  • Other local functions

Example 1

class Program{
   public static void Main(){
      void addTwoNumbers(int a, int b){
         System.Console.WriteLine(a + b);
      }
      addTwoNumbers(1, 2);
      Console.ReadLine();
   }
}

Output

3

Example 2

class Program{
   public static void Main(){
      void addTwoNumbers(int a, int b, out int c){
         c = a + b;
      }
      addTwoNumbers(1, 2, out int c);
      System.Console.WriteLine(c);
      Console.ReadLine();
   }
}

Output

3
raja
Published on 19-Aug-2020 13:48:10
Advertisements