Let us explore Local functions of C# 7.0 inside Visual Studio "15" Preview 2

Rajnilari2015
Posted by in C# category on for Beginner level | Points: 250 | Views : 820 red flag
Rating: 5 out of 5  
 1 vote(s)

In this article, we will explore the Local functions of C# 7.0


 Download source code for Let us explore Local functions of C# 7.0 inside Visual Studio "15" Preview 2

Recommendation
Read A Beginners Guide to work with ASP.NET Web API and AngularJS before this article.

Introduction

Microsoft has announced its Visual Studio Enterprise "15" Preview 2. We have download the same from here After downloading, install the platform installer and the first splash screen will appear as

Click "Install", to bring the next screen

Once done, the last screen will be

It will ask for a system reboot and then we can find the Apps Menu

Clicking on that will ask for signing.Once done, then the VS Environment will open

In this article, we will explore the Local functions of C# 7.0

Enabling experimental features

By default VS15 is using C# 6. So some of the C# 7.0 features won't work. For that to work, we need to add conditional compilation symbols to our project: __DEMO__.

Go to project (here: ConsoleApplication1) >properties > Build > Conditional compilation symbols as shown under

What is Local Function?

Local functions allows us to define a function inside the scope/block of another function. It allows to declare methods and types in block scope just like variables. The concept is very similar to Closure

Using the code

Fire up a "Console Application" and write the below code

using System;

namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {            
            void AddNumbersUsingLocalFunction(int a=10, int b=20)
            {
                Console.WriteLine("Using Local Function : Sum is {0}", a+b);
            }
            AddNumbersUsingLocalFunction(16);
            Console.ReadKey();        
        }
    }
}

The result

As can be figure out that, inside the Main method we have implemented the AddNumbersUsingLocalFunction function. Hence it's scope is bounded inside that block only. We have used Optional Parameter here for the Addition operation

How it works internally?

Well when we open in the IDLASM.exe, we find the below

Let us click Main:void(string[]) and we find an interesting stuff

The Main method is invoking the local function which is void ConsoleApplication1.Program::'<Main>g__AddNumbersUsingLocalFunction0_0'(int32,int32).In other word, the local function is blocked by the Main() method

When we open <Main>g__AddNumbersUsingLocalFunction0_0:void(int32,int32) we find

So that's the scope of the Local Function.

What kind of Access Modifiers we can use in the local function?

We can use only

  1. Unsafe

    	static void Main(string[] args)
            {
                unsafe void AddNumbersUsingLocalFunction(int a=10, int b=20)
                {
                    Console.WriteLine("Using Local Function : Sum is {0}", a+b);               
    
                }
    
                AddNumbersUsingLocalFunction(16);
                Console.ReadKey();        
            }
    		
  2. Async

    	static void Main(string[] args)
            {
                async void AddNumbersUsingLocalFunction(int a = 10, int b = 20)
                {
                    // This method runs asynchronously.
                    int sum = await Task.Run(() => a+b);
                    Console.WriteLine("Using Local Function : Sum is {0}", sum);
                }
                AddNumbersUsingLocalFunction(16);
                Console.ReadKey();        
            }
            

For any other access specifier (like public,partial,static, virtual etc.) it won't work

Usage of Iterator functions with Local Functions

We will use the Yield statement for generating the numbers to find the factorial of a number. The program also demonstrates multiple local functions inside a single block

using System;
using System.Collections.Generic;

namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
            IEnumerable<int> Factorial(int number)
            {
                int startIndex = 1;

                //loop continues till the condition becomes false
                while (startIndex <= number)
                {
                    yield return startIndex;
                    startIndex++;
                }
            }

            void FactorialUsingLocalFunction(int number)
            {
                int input = number; //Factorial of the number to find
                int fact = 1; //a temporary variable to store the intermediate computed values            

                foreach (var n in Factorial(input))
                {
                    fact *= n;
                }

                //display the result
                Console.WriteLine("Factorial of {0} is {1}", input, fact);

            }
            FactorialUsingLocalFunction(4);            
            Console.ReadKey();        
        }
    }
}

Some more features currently supported by Local Function

  1. We can use Caller info attributes on parameters
  2. Local functions can be generic.
  3. Support for optional/default/named arguments
  4. Can capture variables (like a lambda)
  5. It can be recursive
  6. Supports Expression Bodied Function
  7. Support for Iterator functions
  8. Support for Async functions
  9. And many more

Reference

Local Functions #2930

Conclusion

It will be too early to say whether in the final release this feature of C# 7.0 will be there or not; but , however, it's a nice feature being available in C# 7.0 in Visual Studio Enterprise "15" Preview 2. Hope we all have enjoyed the article.Thanks for reading. Zipped file attached.

Recommendation
Read Let's know about ComputerInfo Class after this article.
Page copy protected against web site content infringement by Copyscape

About the Author

Rajnilari2015
Full Name: Niladri Biswas (RNA Team)
Member Level: Platinum
Member Status: Member,MVP
Member Since: 3/17/2015 2:41:06 AM
Country: India
-- Thanks & Regards, RNA Team


Login to vote for this post.

Comments or Responses

Login to post response

Comment using Facebook(Author doesn't get notification)