How To Achieve The Local Function In Older Versions Of C# 7.0

In C# 7.0, they provided a new feature called local function. If you want to reuse the set of codes within the function, it will be useful.

To learn about the local function, refer to this URL.

The sample code for local function is given below.

  1. static void Main(string[] args) {  
  2.     int ShowMessage() {  
  3.         Console.WriteLine("The message from local function.");  
  4.     }  
  5.     ShowMessage();  
  6.     Console.ReadKey();  
  7. }  

Characteristics and rule of local function

  1. The local function is capable of accessing the parameter and local variable of the parent function.
  2. If you want access the local variable into the local function, it should be declared before local function definition.
  3. The local functions should be declared before calling it.
  4. All other characteristics of the function are applicable to the local function.

Thus, if you want to achieve this feature on older versions of C# 7.0, you can do it, using a delegate, as shown below. 

  1. static void Main(string[] args) {  
  2.     MethodRef localMethod = new MethodRef(delegate() {  
  3.         Console.WriteLine("The message from local function.");  
  4.     });  
  5.     localMethod();  
  6.     Console.ReadKey();  
  7. }  

Please feel free to ask any questions regarding local function. You can share, if you know anything about local function usage.

Next Recommended Reading C# 7.0 New Feature - Tuples In C# 7