C# Local Functions - Why And When To Use Them

Introduction

 
Here we will cover why we need local functions and how they could improve your application performance. You will learn when you should choose Local Function over Lambda expression (Delegates). You will understand how the IL code looks when we execute our code with Lambda expression and local functions. 
 

Scenario 1

 

Using Lambda Expression

 
Consider a scenario where you have a list of items with buying and selling price & you want to calculate the percentage of profit of all the items individually.
 
So, we have a class which represents order details (Flatten object):
  1. public class OrderDetails  
  2.        {  
  3.            public int Id { getset; }  
  4.   
  5.            public string ItemName { getset; }  
  6.   
  7.            public double PurchasePrice { getset; }  
  8.   
  9.            public double SellingPrice { getset; }  
  10.   
  11.            public OrderDetails()  
  12.            {  
  13.            }  
  14.        }  
We have a list of items, we will iterate each item and calculate the percentage of profit for each item:
  1. static void Main(string[] args)  
  2.         {  
  3.              //#1. Create a list Ordered items details  
  4.             List<OrderDetails> lstOrderDetails = new List<OrderDetails>();  
  5.   
  6.             lstOrderDetails.Add(new OrderDetails() { Id = 1, ItemName = "Item 1", PurchasePrice = 100, SellingPrice = 120 });  
  7.             lstOrderDetails.Add(new OrderDetails() { Id = 2, ItemName = "Item 2", PurchasePrice = 800, SellingPrice = 1200 });  
  8.             lstOrderDetails.Add(new OrderDetails() { Id = 3, ItemName = "Item 3", PurchasePrice = 150, SellingPrice = 150 });  
  9.             lstOrderDetails.Add(new OrderDetails() { Id = 4, ItemName = "Item 4", PurchasePrice = 155, SellingPrice = 310 });  
  10.             lstOrderDetails.Add(new OrderDetails() { Id = 5, ItemName = "Item 5", PurchasePrice = 500, SellingPrice = 550 });  
  11.   
  12.             //#2. A Lambda to calculate Profit Percentage 
  13.             Func<doubledoubledouble> GetPercentageProfit = (purchasePrice, sellPrice) =>  (((sellPrice - purchasePrice) / purchasePrice) * 100);  
  14.   
  15.             //#3. Loop through each item and print the profit details by calling our delegate  
  16.             foreach(var order in lstOrderDetails)  
  17.             {  
  18.                 Console.WriteLine($"Item Name: {order.ItemName}, Profit(%) : {GetPercentageProfit(order.PurchasePrice, order.SellingPrice)} ");  
  19.             }  
  20.   
  21.             Console.ReadLine();  
  22.         }  
In #2 above, we have created a Lambda expression which calculates the percentage of profit and we are calling it in the #3 "foreach" loop. 
 
Now let's see how this Lambda Expression looks in the IL(Intermediate Language) code, and what it does behind the scenes.
 
To check that, we will use ILDASM.exe, which ships with the .Net framework. You can find it here: "C:\Program Files (x86)\Microsoft SDKs\Windows\v10.0A\bin\NETFX 4.8 Tools" Or you can attach it in your visual studio tools as an extension (I am not covering that, if anyone want to know then please ask in the comments):
 
 
I am running it from my Visual Studio 2019 as I added it as an extension:
 
 
Then I am opening the dll file of my project "Local Function.dll" in ILDASM tool:
 
Double click on your "Main : void(string[])" function, it will open the IL code in a new window, see the marked code below:
 
  1. You can see that our lambda expression is converted into class. Why? Because lambda expressions are converted to delegates.
  2. As it is a class, we should use it by an instance, which we are getting from "new obj". IT means it will be allocated on Heap.
  3. To execute/invoke this method, The IL code uses "callvirt" (We will cover callvirt (call virtual method) later with Local Function implementation) 
Now, we got to know that Lambda is converted into the delegate and then class, and we need an instance of this class to use it further. The lifecycle of these objects will have to be handled by the Garbage collector.
 

Using Local Function

 
Here we replaced Lambda expression with "Local Function":
  1. static void Main(string[] args)  
  2. {  
  3.     //#1. Order details  
  4.     List<OrderDetails> lstOrderDetails = new List<OrderDetails>();  
  5.   
  6.     lstOrderDetails.Add(new OrderDetails() { Id = 1, ItemName = "Item 1", PurchasePrice = 100, SellingPrice = 120 });  
  7.     lstOrderDetails.Add(new OrderDetails() { Id = 2, ItemName = "Item 2", PurchasePrice = 800, SellingPrice = 1200 });  
  8.     lstOrderDetails.Add(new OrderDetails() { Id = 3, ItemName = "Item 3", PurchasePrice = 150, SellingPrice = 150 });  
  9.     lstOrderDetails.Add(new OrderDetails() { Id = 4, ItemName = "Item 4", PurchasePrice = 155, SellingPrice = 310 });  
  10.     lstOrderDetails.Add(new OrderDetails() { Id = 5, ItemName = "Item 5", PurchasePrice = 500, SellingPrice = 550 });  
  11.     
  12.     //#2. Loop through each item and get the profit details  
  13.     foreach (var order in lstOrderDetails)  
  14.     {  
  15.         Console.WriteLine($"Item Name: {order.ItemName}, Profit(%) : {GetPercentageProfit(order.PurchasePrice, order.SellingPrice)} ");  
  16.     }  
  17.   
  18.     //#3. Local function  - Inside the function "Main"  
  19.     double GetPercentageProfit(double purchasePrice, double sellPrice)  
  20.     {  
  21.         return (((sellPrice - purchasePrice) / purchasePrice) * 100);  
  22.     }  
  23.   
  24.     Console.ReadLine();  
  25. }  
So, at #3 above, we have implemented the Local Function, which is embedded inside the Main Function. Let's run the ILDASM.exe again to check how this local function has converted into IL,
 
 
See there is no new class, no new object. Its just a simple method/function call. There is no new object needed to call this method. It would save some memory. The other important difference between the Lambda expression and this Local Function is how the framework is calling this method in IL. Here it is called as "call", which is faster than "callvirt". Why?  Because it is stored on Stack not on Heap (Lambda expression instance is on Heap). (Both call and callvirt are IL instructions)
 
I know as a developer you don't need to focus on how the compiler/IL is calling the method, but I strongly feel that for writing very performant applications, you should know the internal details of Framework.
 
So the difference between call and callvert is, the call IL instruction. Always try to call this method whether the instance variable which is going to call this method is null or not. It does not check the existence of this caller instance. callvirt always checks the reference before calling the actual method under the hood. So, we can say callvirt cannot call the static class method, it can only call instance methods.

Scenario 2

Consider a scenario where you want to use iterators in your logic (using "yield" keyword in the "foreach" loop). We are considering the same example of order details, where we need to iterate to all the items and print its selling price. We will add a check on the items list that it should not be null, It should have at least one element.
  1. static void Main(string[] args)  
  2.        {  
  3.            //#1. Order details  
  4.            List<OrderDetails> lstOrderDetails = new List<OrderDetails>();  
  5.            lstOrderDetails.Add(new OrderDetails() { Id = 1, ItemName = "Item 1", PurchasePrice = 100, SellingPrice = 120 });  
  6.            lstOrderDetails.Add(new OrderDetails() { Id = 2, ItemName = "Item 2", PurchasePrice = 800, SellingPrice = 1200 });  
  7.            lstOrderDetails.Add(new OrderDetails() { Id = 3, ItemName = "Item 3", PurchasePrice = 150, SellingPrice = 150 });  
  8.            lstOrderDetails.Add(new OrderDetails() { Id = 4, ItemName = "Item 4", PurchasePrice = 155, SellingPrice = 310 });  
  9.            lstOrderDetails.Add(new OrderDetails() { Id = 5, ItemName = "Item 5", PurchasePrice = 500, SellingPrice = 550 });  
  10.   
  11.            //#2. Get Item Selling Price  
  12.            var result = GetItemSellingPice(lstOrderDetails);  
  13.              
  14.            //#4. Print Item name with its selling price  
  15.            foreach(string s in result)  
  16.            {  
  17.                Console.WriteLine(s.ToString());  
  18.            }  
  19.   
  20.            Console.ReadLine();  
  21.        }  
  22.   
  23.        /// <summary>  
  24.        /// Method to return the item name with price  
  25.        /// </summary>  
  26.        /// <param name="lstOrderDetails"></param>  
  27.        /// <returns></returns>  
  28.        public static IEnumerable<string> GetItemSellingPice(List<OrderDetails> lstOrderDetails)  
  29.        {  
  30.            //#3. If List is empty then throw Argument null exception  
  31.            if (lstOrderDetails == nullthrow new ArgumentNullException();  
  32.   
  33.            foreach (var order in lstOrderDetails)  
  34.            {  
  35.                yield return ($"Item Name:{order.ItemName}, Selling Price:{order.SellingPrice}");  
  36.            }  
  37.        }  
So, in the above code, we have a list of 5 items, we are passing it to the method "GetItemSellingPice" to get the item's price. You can see that we are applying validation that this list should not be null and we are using yield return in for loop. When we run the application we get the following output,
 
 
All looks good here, right?
 
Now consider a scenario where your order details list is null. So, when we call the method "GetItemSellingPice" it should return the ArgumentNullException as List is null. But this is not the case, when you use iterators, It does not execute right away. It starts executing when you start processing its"result". So in the code below we are making the lstOrderDetails as null: 
  1. static void Main(string[] args)  
  2.        {  
  3.            //#1. Order details  
  4.            List<OrderDetails> lstOrderDetails = null;  
  5.   
  6.            //#2. Get Item Selling Price - NO ArgumentNullException HERE  
  7.            var result = GetItemSellingPice(lstOrderDetails);  
  8.              
  9.            //You can do any work here  
  10.   
  11.            //#4. ArgumentNullException HERE, when we start using the result property  
  12.            //Print Item name with its selling price  
  13.            foreach (string s in result)  
  14.            {  
  15.                Console.WriteLine(s.ToString());  
  16.            }  
  17.   
  18.            Console.ReadLine();  
  19.        }  
  20.   
  21.        /// <summary>  
  22.        /// Method to return the item name with price  
  23.        /// </summary>  
  24.        /// <param name="lstOrderDetails"></param>  
  25.        /// <returns></returns>  
  26.        public static IEnumerable<string> GetItemSellingPice(List<OrderDetails> lstOrderDetails)  
  27.        {  
  28.            //#3. If List is empty then throw Argument null exception  
  29.            if (lstOrderDetails == nullthrow new ArgumentNullException();  

  30.           //#5. Loop through each item
  31.            foreach (var order in lstOrderDetails)  
  32.            {  
  33.                yield return ($"Item Name:{order.ItemName}, Selling Price:{order.SellingPrice}");  
  34.            }  
  35.        }  
The above code will not throw exception at #2. It will thrown on #4, where we start working on the resulting property "result". So, What could be the solution to that? Local Functions is the solution. Here is the code:
  1. static void Main(string[] args)  
  2.         {  
  3.             //#1. Order details  
  4.             List<OrderDetails> lstOrderDetails = null;  
  5.   
  6.             //#2.  Get Item Selling Price - EXCEPTION WILL CATCH HERE ONLY  
  7.             var result = GetItemSellingPice(lstOrderDetails);  
  8.   
  9.             //4. Print Item name with its selling price  
  10.             foreach(string s in result)  
  11.             {  
  12.                 Console.WriteLine(s.ToString());  
  13.             }  
  14.   
  15.             Console.ReadLine();  
  16.         }  
  17.   
  18.         /// <summary>  
  19.         /// Method to return the item name with price  
  20.         /// </summary>  
  21.         /// <param name="lstOrderDetails"></param>  
  22.         /// <returns></returns>  
  23.         public static IEnumerable<string> GetItemSellingPice(List<OrderDetails> lstOrderDetails)  
  24.         {  
  25.             //#3. If List is empty then throw Argument null exception  
  26.             if (lstOrderDetails == nullthrow new ArgumentNullException();  
  27.   
  28.             //Calling Local Function  
  29.             return GetItemPrice();  
  30.               
  31.             //#4. Local Function  
  32.             IEnumerable<string> GetItemPrice()  
  33.             {  
  34.                 foreach (var order in lstOrderDetails)  
  35.                 {  
  36.                     yield return ($"Item Name:{order.ItemName}, Selling Price:{order.SellingPrice}");  
  37.                 }  
  38.             }  
  39.         }  
You can see that we moved the foreach loop block into Local Function. So, when we execute it, we will get the exception at #3, if the list is null. This is the eager validation for iterators.
 

Conclusion

 
Local Function is a very powerful feature. We learned about the performance as compared to Lambda expression, and we got to know about validations in iterators. A Local function could be recursive, while Lambda expression is not meant to be recursive, so it could solve many of your problems. 


Similar Articles