New C# 7.0 Features. Local Functions

C# 7.0 Local FunctionsC# 7.0 is coming! Even 6.0 is not released yet, you can already try new C# 7.0 features. To do that you need:

  • Visual Studio 15 preview
  • Set __DEMO__ and __DEMO_EXPERIMENTAL__ as Conditional compilation symbol in project settings.

Not all of the new features available in current preview, but you can already play with some of them.

But today we gonna look closer at

Local Functions

or shorter:

or even like that:

Do you like it? I do!

You can define local method in any scope and it will be available only in that scope (and in all inner scopes as well, the same as local variable).

You will have access to all outer scope’s variables and methods (see below how it is implemented).

Benefits

  • Small helper methods required only in some scope (usually with LINQ expression)
  • No GC allocations comparing to anonymous methods and lambda expressions
  • You can pass ref and out parameters (comparing to anonymous methods and lambda expressions)

Let’s look closer what is under the hood.

IL code

After disassembling first example with ildasm.exe I found following:

As you can see that LocalFunction is a regular instance method with specific name ‘<Main>g__LocalFunction0_0’ and CompilerGenerated attribute. Here is C# equivalent:

Because LocalFunction was declared in a static context, the method is also static. If you define it inside instance method it will also be comliped to instance method.

The third example (using outer scope variable) will show us a bit different IL:

As you can see, compiler created an inner struct and uses it to pass “outer scope” variable(s) to the local function as an implicit parameter. Here is C# equivalent:

That is why you cannot declare variables in local function which has the same name as a variable declared in outer scope.

In fact, it does not matter in what scope it was declared. It can be for loop, if, while, curly brackets {} or other local function. For each outer scope will be created a structure to hold all scope related variables.

Leave a Reply

Your email address will not be published. Required fields are marked *