Creating Local Functions

Functions that are created within a function are known as Local Functions. These are mainly used when defining helper functions that have to be in the scope of the function itself. The following example shows how the factorial of the number can be obtained by writing a Local Function and calling it recursively:

static void Main(string[] args) 
{ 
  Console.WriteLine(ExecuteFactorial(4));          
} 
 
static long ExecuteFactorial(int n) 
{ 
  if (n < 0) throw new ArgumentException("Must be non negative", 
nameof(n)); else return CheckFactorial(n); long CheckFactorial(int x) {
    if (x == 0) return 1; 
    return x * CheckFactorial(x - 1); 
  } 
}
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.218.74.199