C# 7 Features - Local Functions

With the Visual Studio 15 (Visual Studio 2017 RC) preview available, some features of new version of C#; i.e. version 7.0, are also available. Let's try to review some of the expected available features. 
 
We will start with the concept of local functions. The concept is nothing but creating a function within a function, like we normally do inside a class. We will create a method GetSalary. The code will look like the following.
  1. static void Main(string[] args)  
  2. {  
  3.    Console.WriteLine("Salary is: " + GetSalary());  
  4. }  
  5. public static Int32 GetSalary()  
  6. {  
  7.   return 20000;  
  8. }  
Next, we need to add some bonus to the salary, based on some calculation. For this, we will have a method which will return some integer value. This result will be added to the actual salary and the complete result will be returned.
 
The main point here is that if we create a public method to calculate the bonus, it will be globally available. If we create a private method, the method will be available to other methods as well, which is not required. So, what we will do is create the method as a sub-method within the GetSalary function. This will be created like any other normal function. So, the code will look like the following.
  1. namespace ConsoleApplication1  
  2. {  
  3.     class Program  
  4.     {  
  5.         static void Main(string[] args)  
  6.         {  
  7.             Console.WriteLine("Salary is: " + GetSalary());  
  8.         }  
  9.         public static Int32 GetSalary()  
  10.         {  
  11.             var salary = GetBonus() * 2;  
  12.   
  13.             return salary;  
  14.   
  15.             Int32 GetBonus()  
  16.             {  
  17.                 return 10000;  
  18.             }  
  19.         }  
  20.     }  
As we saw above, we have created another method within a function. So, there is no need to create extra functions. Just run the code and see the results. Happy coding!!!  


Similar Articles