Working With Local Functions In C# 7.0

I am here to start a series related C# 7.0 features. Today, we will be going through one of the features called Local Functions and will demonstrate the uses in an easy way.

Local Function

Local function is a kind of inner function, sub-function or function within a function that can be declared and defined within parent method. We have the inner class concept from quite some time. Noe, it has been propagated to function as well.

Any piece of code that is required only on any particular method can be put as an inner function. The few examples could be,

  • Small helper function to be used several times in a main or parent method.
  • Parameter validation function for any iterators or asynchronous method.
  • An alternate to recursive functions as local function comparatively takes less memory due to reduced call stack.

The below diagram depicts the scope of variety of functions.

C# 7.0

Features of Local function

  • Local function can be declared and defined inside any method, constructor, and properties.
  • In the runtime, compiler translates Local function as static method; hence they can’t be declared as static explicitly.
  • Local function supports generics, ref/out etc.

Is Local function concept really new?

Not really, it was kind of possible with Func and Action delegate even in older versions of C# but with some constraints. For example,

  • Func and Action can’t use the generics
  • Func and Action can’t use ref and out parameters
  • Func and Action can’t use params and optional parameters.
  • Calling Func and Action has more memory overhead than Local functions.

Working with Local Function

Enough theory! Now, let’s look at how to work with them.

The below code snippet shows two examples, one with regular way (i.e. GetFullAddress) and another using local function (GetFullAddressUsingLocalFunc).

  1. class Program  
  2.     {  
  3.         static void Main(string[] args)  
  4.         {  
  5.             Console.WriteLine("Full Address: " + LocalFunc.GetFullAddress());  
  6.             Console.WriteLine("Full Address using Local Function: " + LocalFunc. GetFullAddressUsingLocalFunc());  
  7.         }  
  8.   
  9. class LocalFunc  
  10.     {  
  11. public static string GetFullAddress()  
  12.         {  
  13.             return "Gram/Post-Beeda, Via-Amarpatan, District - Satna, MP";  
  14.         }  
  15.   
  16.         public static string GetFullAddressUsingLocalFunc()  
  17.         {  
  18.             var fullAddr = GetBasicAddress() + ", District - Satna, MP";  
  19.   
  20.             return fullAddr;  
  21.   
  22.             string GetBasicAddress()  
  23.             {  
  24.                 return "Gram/Post-Beeda, Via-Amarpatan";  
  25.             }  
  26.         }  
  27.     }  
Output

C# 7.0

As you can see in the above example that output is same in both the methods and GetBasicAddress is a Local function that returns the part of the address. Then, the parent method adds more to it and returns to the caller.

Let’s take one more example that shows the factorial calculation using Local function.

  1. Console.WriteLine("Factorial using Local Function: " + LocalFunc.GetFactorialUsingLocalFunction(5));  
  2.   
  3. public static long GetFactorialUsingLocalFunction(int num)  
  4.         {  
  5.             if (num < 0)  
  6.             {  
  7.                 throw new ArgumentException("Invalid number!", nameof(num));  
  8.             }  
  9.             else if (num == 0)  
  10.             {  
  11.                 return 1;  
  12.             }  
  13.   
  14.             long fact = num;  
  15.             while (num > 1)  
  16.             {  
  17.                 Multiply(num - 1);  
  18.                 num--;  
  19.             }  
  20.   
  21.             void Multiply(int x)  
  22.             {  
  23.                 fact *= x;  
  24.             }  
  25.             return fact;  
  26.         }  
Output

C# 7.0
 

As you can see, the Local function "Multiply" is used in calculating factorial.

Conclusion

In this article, we have discussed the features of local functions and where these can be used. We have also explained how local function is better than available constructs to do similar job. In the end, we have demonstrated how it can be used.

You can also download the attached demo project (LocalFunc.zip) to go through the full source code referred in the article.

Hope you have liked the article. Look forward for your comments/suggestions.


Recommended Free Ebook
Similar Articles