Static Local Functions

Local Functions were introduced in C# 7.0. You can read more about it here at my previous article. In C# 8.0, these Local Functions are improvised so that they will work more towards bettering the performance when passing parameters from the containing method.
 
For an example, let’s see the below code block. 
  1. public void PrintName(string name)  
  2. {  
  3.     Console.WriteLine($"You Name is: {name}");  
  4.     SayHello();  
  5.   
  6.     void SayHello()  
  7.     {  
  8.         Console.WriteLine($"Hello {name}!");  
  9.     }  
  10. }  
With the above code block, we are trying to print the name as passed to the method PrintName as a parameter and also greeting “Hello” to the same name. Here, we are using the same name parameter from the calling method in the local function.
 
At Runtime, when it starts executing PrintName() method, it will keep this information to the Stack memory including the variables scoped for this method. Similarly, in the case of SayHello(). But, here as we are using the parent variables, the runtime will copy these variables in to SayHello() stack memory. It means we are copying these variables to local variables. In our case, we are passing only name string variable to the local function. We cannot see much performance but when we are passing huge objects, we can feel the performance.
 
In C# 8.0, we addressed this issue by declaring the local functions as static since we are aware that static methods won’t be allocating separate memory in each object and the same in its variables scoped to it.
 
By using static local functions, we can rewrite the same logic as below.
  1. public void PrintName(string name)  
  2. {  
  3.     Console.WriteLine($"You Name is: {name}");  
  4.     SayHello(name);  
  5.   
  6.     static void SayHello(string name)  
  7.     {  
  8.         Console.WriteLine($"Hello {name}!");  
  9.     }  
  10. }  
Here, we are passing the name variable as a parameter to the static local function. This way, the local functions do not depend on their calling variables and perform well at runtime with their own scope of variables/objects.
 
Happy Coding ??
Author
Sai Kumar Koona
239 8k 1.6m
Next » 'Nullable Enable' To Avoid Null Reference Exception