Sunday, January 8, 2017

C# 7 features - Local functions


A preview of C# 7.0 has been introduced with the preview release of Visual Studio 15. This should not be confused with Visual studio 2015, as it is separate.

In order to install visual studio 15, you will have to download the setup from the link here - https://blogs.msdn.microsoft.com/vcblog/2016/10/05/visual-studio-15-preview-5-now-available/ and install the web and desktop development tools.

So we will start with the first feature which is the use of Local functions. Normally we create private sub-functions for code refactoring. However, these functions are exposed to other methods in the class, even though they are not required to use. But in C# 7, we can have functions within the functions. Yes, we can create a function within another function.

For example, following code is valid in C# 7.0:

        static void Main(string[] args)
        {
            var d = GetSalary();
        }
        public static Int32 GetSalary()
        {
            var s = GetSum(10, 6) * 2;

            return s;

            Int32 GetSum(Int32 a, Int32 b)
            {
                return a + b;
            }
        }

Run the code and you will get 32 as output.


Here, we have the GetSum method, which will return the sum of two numbers. The result is then multiplied by 2. Hope you enjoyed reading it. Happy coding...!!!

No comments:

Post a Comment