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.
- static void Main(string[] args)
- {
- Console.WriteLine("Salary is: " + GetSalary());
- }
- public static Int32 GetSalary()
- {
- return 20000;
- }
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.
- namespace ConsoleApplication1
- {
- class Program
- {
- static void Main(string[] args)
- {
- Console.WriteLine("Salary is: " + GetSalary());
- }
- public static Int32 GetSalary()
- {
- var salary = GetBonus() * 2;
- return salary;
- Int32 GetBonus()
- {
- return 10000;
- }
- }
- }

Ranjith VPosted Apr 8, 2017, 1:51 PM
Hi Jasminder, Thanks for your information. But I have a question. Why would we want to write a method within a function? In the example code you have given, we can simply multiply 1000 with 2 in the GetSalary() method itself. Kindly give us an example scenario where a private function will really be of some use.
Manav PandyaPosted Feb 2, 2017, 12:15 AM
Worth reading stuff sir @jasminder Singh